Recursive template instantiation error--help!
Sam Varshavchik
mrsam@courier-mta.com
Mon Jan 9 10:06:00 GMT 2012
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;
};
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20120109/d3f7907e/attachment-0001.sig>
More information about the Gcc-help
mailing list