是否有编译无限时间的C ++代码?

时间:2015-01-03 11:32:09

标签: c++ templates compilation turing-machines

我经常听说" C ++源代码需要花费大量的时间和内存来编译#34;

我也听说C ++模板是Turing完成的,所以它可能会受Halting problem的影响。

我还构建了一个C ++项目,需要花费8 GiB的内存和2小时的时间。

所以,问题是:是否存在可以无限时间编译的C ++代码?

(嵌套包含或嵌套模板是可检测的,因此不应计算。)

相关问题:Is there a C++ code that compiles with infinite memory?(我将它们分开,因为我期待不同的答案。)

1 个答案:

答案 0 :(得分:8)

理论上,这将编译为“无限”。时间因为模板扩展是无限递归的:

template <size_t N>
struct eat
{
    static constexpr size_t value = eat<N+1>::value;
};

但是,我使用的所有编译器都会对这种代码进行防御,发出的错误很像:

/Users/richardh/Documents/dev/Scratchpad/tryit/tryit/words.cpp:136:37: fatal error: recursive template instantiation exceeded maximum depth of 256
    static constexpr size_t value = eat<N+1>::value;
                                    ^
/Users/richardh/Documents/dev/Scratchpad/tryit/tryit/words.cpp:136:37: note: in instantiation of template class 'eat<257>' requested here
    static constexpr size_t value = eat<N+1>::value;
                                    ^
/Users/richardh/Documents/dev/Scratchpad/tryit/tryit/words.cpp:136:37: note: in instantiation of template class 'eat<256>' requested here
    static constexpr size_t value = eat<N+1>::value;
                                    ^
/Users/richardh/Documents/dev/Scratchpad/tryit/tryit/words.cpp:136:37: note: in instantiation of template class 'eat<255>' requested here
    static constexpr size_t value = eat<N+1>::value;
                                    ^
/Users/richardh/Documents/dev/Scratchpad/tryit/tryit/words.cpp:136:37: note: in instantiation of template class 'eat<254>' requested here
    static constexpr size_t value = eat<N+1>::value;

...等

编辑: 好吧,我认为这个真的是无限的:

template <class T>
struct eat2
{
    using inner = eat2<eat2<T>>;
    static constexpr int value() {
        return inner::value();
    }
};

int main()
{
    eat2<int> e;
    cout << e.value() << endl;
    return 0;
}