C++ 模板图灵完备?

我听说 C++ 中的模板系统在编译时是图灵完备的.这在这篇文章和维基百科.

I'm told that the template system in C++ is Turing-complete at compile time. This is mentioned in this post and also on wikipedia.

您能否提供一个利用此属性进行计算的重要示例?

Can you provide a nontrivial example of a computation that exploits this property?

这个事实在实践中有用吗?

Is this fact useful in practice?

推荐答案

示例

#include <iostream>

template <int N> struct Factorial
{
    enum { val = Factorial<N-1>::val * N };
};

template<>
struct Factorial<0>
{
    enum { val = 1 };
};

int main()
{
    // Note this value is generated at compile time.
    // Also note that most compilers have a limit on the depth of the recursion available.
    std::cout << Factorial<4>::val << "
";
}

这有点有趣,但不太实用.

That was a little fun but not very practical.

回答问题的第二部分:
这个事实在实践中有用吗?

简答:有点.

长答案:是的,但前提是您是模板守护进程.

Long Answer: Yes, but only if you are a template daemon.

使用模板元编程来实现对其他人真正有用的良好编程(即库)真的很难(尽管可行).To Help boost 甚至有 MPL aka (Meta编程库).但是尝试在您的模板代码中调试编译器错误,您会遇到很长时间的困难.

To turn out good programming using template meta-programming that is really useful for others to use (ie a library) is really really tough (though do-able). To Help boost even has MPL aka (Meta Programming Library). But try debugging a compiler error in your template code and you will be in for a long hard ride.

但是它被用于有用的东西的一个很好的实际例子:

But a good practical example of it being used for something useful:

Scott Meyers 一直在使用模板工具对 C++ 语言进行扩展(我使用的术语是松散的).您可以在此处阅读他的工作Enforcing Code Features'

Scott Meyers has been working extensions to the C++ language (I use the term loosely) using the templating facilities. You can read about his work here 'Enforcing Code Features'

相关文章