c++ - 是否有可以无限期编译的 C++ 代码?

标签 c++ templates compilation turing-machines

我经常听说“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/

相关文章:

c++ - 使用可变参数模板的平方和

c++ - 如何实现列表<T>::迭代器?

c++ - DLL 存在时出现 System.DLLNotFoundException

c++ - 如何从二进制文件中读取多个结构

c++ - 了解 TM 模拟器

compilation - 在树莓派上编译p0sixspwn的问题

android - 任务 'Project:processDebugManifest' 的 Gradle 执行失败

compilation - 不使用 mpirun 运行 OpenMPI 程序

java - 我可以在不编译的情况下获得 C/C++/Java 代码的 XML AST 吗?

c++ - 如何在退出时调试 CorExitProcess 中的访问冲突 0xC0000005?