iam*_*ind 5 c++ compiler-construction recursion templates
这个问题只是出于好奇.在递归模板中如果我们忘记放置一个特定的特化,那么编译器将进行大量的迭代然后在某个时候停止并给出错误,例如,
error: incomplete type ‘X<-0x000000000000001ca>’ used in nested name specifier
Run Code Online (Sandbox Code Playgroud)
在某些情况下,编译是无限的.例如,请参阅以下代码(仅用于说明;使用gcc 4.4.1编译):
template<int I>
struct Infinite
{
enum { value = (I & 0x1)? Infinite<I+1>::value : Infinite<I-1>::value };
};
int main ()
{
int i = Infinite<1>::value;
}
Run Code Online (Sandbox Code Playgroud)
难道编译器不够聪明,不能在某个时候停止吗?
编辑:上面显示的编译错误是针对其他代码的.对于示例代码,编译永远不会停止(但是,我会在两者之间看到这样的错误)
使用模板将解析器置于无限循环中并不新鲜.
// Stresses the compiler infinitely
// from: http://www.fefe.de/c++/c%2b%2b-talk.pdf
template<class T> struct Loop { Loop<T*> operator->(); };
Loop<int> i, j = i->hooray;
Run Code Online (Sandbox Code Playgroud)