【问题标题】:Is there a C++ code that compiles for infinite time?是否有可以无限编译的 C++ 代码?
【发布时间】:2015-01-03 21:33:22
【问题描述】:

我经常听到“C++ 源代码需要大量时间和内存来编译”。

我还听说 C++ 模板是图灵完备的,所以它可能会受到 Halting problem 的影响。

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

所以,问题是:是否有可以无限编译的 C++ 代码?

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

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

【问题讨论】:

  • 怎么会有人知道 - 但我想你可以等到它完成?
  • 从理论上讲,可能可以创建一些源代码,用于通用和纯 C++ 编译器将花费无限时间进行编译。实际上并使用现代编译器?可能是不可能的。
  • 根据定义,如果编译需要无限时间,那么编译不会在有限时间内完成。
  • 由于 C++ 模板本身如果图灵完备,它会遭受“停止问题”(谷歌它)。那么是否有一个有效的 C++ 程序可以满足使编译器永不停止的条件呢? @EdHeal
  • 您的两个问题确实是独立的问题,但它们之间有一个含义:从有限的块中分配无限的内存需要无限的时间(或者相反,如果您愿意,如果编译在有限时间内终止,看看使用了多少内存:这是编译所需的内存量)。所以你可以从一个问题开始。

标签: c++ templates compilation turing-machines


【解决方案1】:

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

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;
}

【讨论】:

  • 即使你增加递归深度(对我来说它可以达到 1139),这也不会是无限的,因为size_t 有一组有限的值。
  • 公平地说,一旦 N 在 2^64 次(在我的编译器上)迭代后翻转,它将(理论上)停止编译。
  • @filmor 一旦值达到 size_t 的最大值,扩展该代码以添加带有新计数器的新模板参数是微不足道的。
  • 我已经读过另一个类似 stackoverflow.com/a/6079650/2557927 的例子。感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多