我经常听说“C++ 源代码需要大量时间和内存来编译”。
我还听说 C++ 模板是图灵完备的,所以它可能会遇到 Halting problem 问题.
我还构建了一个耗时 8 GiB 内存和 2 小时时间的 C++ 项目。
那么,问题是:是否存在可以无限期编译的 C++ 代码?
(嵌套的包含或嵌套的模板是可检测的,所以它们不应该算在内。)
相关问题:Is there a C++ code that compiles with infinite memory? (我将它们分开,因为我希望得到不同的答案。)
最佳答案
理论上这将编译“无限”时间,因为模板扩展是无限递归的:
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;
}
关于c++ - 是否有可以无限期编译的 C++ 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27754352/