与模板的无限编译 [英] Infinite compilation with templates

查看:119
本文介绍了与模板的无限编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题只是出于好奇心。在递归模板中,如果我们忘记了一个特定的特殊化,那么​​编译器将进行大量的迭代,然后在某个时候停止,并给出错误,如

 错误:不完整类型'X< -0x000000000000001ca>'用于嵌套名称说明符

在某些情况下,编译无限。例如,参见下面的代码(仅仅为了说明;用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;
}

不应该是编译器足够聪明才能在某些时候停止吗?



编辑:上面显示的编译错误是针对其他代码的。对于示例代码,编译永远不会停止(但是我会在中间看到这样的错误)

解决方案

正确地,你希望编译器识别它永远不会停止迭代。除了在固定数量的嵌套类型之后停止,你想要的是不可能的:如果我看到它正确,你可以表达任何图灵机(至少 D 中的模板已完成)。



可以构建一个编译器,确认它会在实际尝试之前嵌套类型,您决定暂停问题是无法判定的然而,我可能会错误地认为你可以把任何计算在参数列表(但模拟一个寄存器机器似乎是可能的,因为我们可以在一个单独的整数模板参数中编码所有寄存器(是的, int 是有限的,但是相当大,这使它几乎无界)。


This question is just out of curiosity. In recursive templates if we forget to put one particular specialization, then compiler will do large number of iterations and then stop at sometime and gives error such as,

error: incomplete type ‘X<-0x000000000000001ca>’ used in nested name specifier

In certain cases, the compilation goes infinite. For example, see the below code (just for illustration; compiled with 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;
}

Should not be compiler smart enough to stop at some time ?

Edit: The compilation error shown above is for other code. For the sample code, compilation never stops (however, I get to see such errors in between)

解决方案

If I understand your question correctly, you want the compiler to recognise that it will never stop iterating. Besides just stopping after a fixed number of nesting types, what you want is provably impossible: If I see it correctly you can express any turing-machine in this fashion (at least the templates in D are turing complete).

So if you can build a compiler that recognises that it will nest types forever before actually trying to, you decide the halting problem which is undecidable for turing-machines.

However, I could very well be mistaken that you can put any computation in the parameter-list (but simulating a register-machine appears to be possible, as we can encode all registers in a separate integer template parameter (yes, int is finite, but quite large, which makes it practically unbounded)).

这篇关于与模板的无限编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆