Patrick Horgan writes:
Building with: g++-4.6.real (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1 This program: template<unsigned int v> class testit{ public: static const unsigned int width = ( v==0 ? 0 : testit<v >> 1>::width + 1); }; int main() { unsigned int foo=testit<3>::width; } Errors out with complaint of exceeding maximum template instantiation depth (error below) even though it seems it should compile like: testit<3> 3==0? No, so width = testit <3 >> 1>::width + 1 ( which would be 1 + 1) testit<1> 1==0? No, so width = testit<1 >> 1>::width+1 (which would be 0 + 1) testit<0> 0==0 so width=0
The problem is that short-circuit evaluation gets carried out only /AFTER/ the entire expression is _fully_ parsed. So:
testit<0>: 0 == 0 ? 0 : testit<0>::width+1;The compiler will then proceed and attempt to expand another instance of testit<0>, which then obviously results in an infinite loop.
The correct way to do this is to use specialization. Instead of the ternary expression, specialize your template:
template<unsigned int v> class testit { public: static const unsigned int width=testit<v >> 1>::width+1; }; template<> class testit<0> { public: static const unsigned int width=0; };
Attachment:
pgpTJfIl7EhDm.pgp
Description: PGP signature