Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 767
user4004359 Avatar asked Feb 03 '26 14:02

user4004359


2 Answers

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 Ts, so value should indeed recurse forever. I don't blame GCC for failing to compile this, in fact it's probably for the best.

like image 179
John Zwinck Avatar answered Feb 05 '26 03:02

John Zwinck


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.

like image 22
user4004359 Avatar answered Feb 05 '26 02:02

user4004359