简体   繁体   中英

gcc fails with template recursion, while clang does not

Comparing clang 3.4.2 and gcc 4.9, which is correct for the following code?

#include <iostream>

template<typename T>
struct SelfRec {
    static const int value = SelfRec<T>::value;
};

int main() {
    std::cout << SelfRec<int>::value << std::endl;
    return 0;
}

clang prints 0, gcc gives typical reached template max depth error.

What could be the meaning of such code? You say Clang prints 0, which is not shocking given that it compiled, but what does the zero mean? Where did it come from?

Note that the static const int value is not a global static variable but exists for each T . And there are infinitely many T s, so value should indeed recurse forever. I don't blame GCC for failing to compile this, in fact it's probably for the best.

According to § 14.7.2/15 this is undefined behavior:

15 There is an implementation-defined quantity that specifies the limit on the total depth of recursive instan- tiations, which could involve more than one template. The result of an infinite recursion in instantiation is undefined.

So I agree with user657267 that either compiler can be "correct". I got the answer from hacker news although I use standard n3337.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM