C ++模板Turing完成? [英] C++ templates Turing-complete?
问题描述
我被告知C ++中的模板系统在编译时是Turing-complete。这在此帖子中以及在 wikipedia 。
你能提供一个利用这个属性的计算的一个非平凡的例子吗?
这个事实在实践中有用吗?
p>
#include< iostream>
template< int N> struct factorial
{
enum {val = Factorial< N-1> :: val * N};
};
模板<>
struct Factorial< 0>
{
enum {val = 1};
};
int main()
{
//注意这个值是在编译时生成的。
//还要注意,大多数编译器对可用递归的深度有限制。
std :: cout<<因子4 :: val< \\\
;
}
这很有趣,但不太实用。
要回答问题的第二部分:
这个事实在实践中是否有用?
简短答案:
长答案:是的,但前提是您是模板守护程序。
使用真正有用的模板元编程来编写良好的编程是非常有用的(即库)是真的很艰难(虽然可以)。要帮助提升,还需要 MPL (元编程库)。但是,请尝试调试模板代码中的编译器错误,并且会花费很长时间。
但是一个很好的实用示例, / p>
Scott Meyers一直使用模板工具来扩展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?
Example
#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 << "\n";
}
That was a little fun but not very practical.
To answer the second part of the question:
Is this fact useful in practice?
Short Answer: Sort of.
Long Answer: Yes, but only if you are a template daemon.
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 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'
这篇关于C ++模板Turing完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!