C++ forever template

Here is a fun little template to crash your compiler. Copy paste it into a file and check out the results.


template <int N>
struct forever {
enum { value = forever<N-1>::value * forever<N-1>::value };
};

enum forever_res { result = forever<1>::value };

Since integer arithmetic wraps this template just expands for all time. On clang the error is pretty neat and well reported:

main.cpp:3:18: fatal error: recursive template instantiation exceeded maximum depth
of 256
enum { value = forever<N-1>::value * forever<N-1>::value };
^
main.cpp:3:18: note: in instantiation of template class 'forever<-255>' requested
here
main.cpp:3:18: note: in instantiation of template class 'forever<-254>' requested
here
main.cpp:3:18: note: in instantiation of template class 'forever<-253>' requested
here
main.cpp:3:18: note: in instantiation of template class 'forever<-252>' requested
here
main.cpp:3:18: note: in instantiation of template class 'forever<-251>' requested
here
main.cpp:3:18: note: (skipping 247 contexts in backtrace; use
-ftemplate-backtrace-limit=0 to see all)
main.cpp:3:18: note: in instantiation of template class 'forever<-3>' requested here
main.cpp:3:18: note: in instantiation of template class 'forever<-2>' requested here
main.cpp:3:18: note: in instantiation of template class 'forever<-1>' requested here
main.cpp:3:18: note: in instantiation of template class 'forever<0>' requested here
main.cpp:6:29: note: in instantiation of template class 'forever<1>' requested here
enum forever_res { result = forever<1>::value };
^
main.cpp:3:18: note: use -ftemplate-depth=N to increase recursive template
instantiation depth
enum { value = forever<N-1>::value * forever<N-1>::value };
^
1 error generated.

Leave a Reply

Your email address will not be published. Required fields are marked *