据我了解,正常的 C++ 代码在编译时被翻译成汇编程序,然后在运行时由 CPU 执行。所以我不是很明白模板元编程的优点有什么大惊小怪的?
维基百科对模板元编程的描述如下:
Template metaprogramming is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates include compile-time constants, data structures, and complete functions. The use of templates can be thought of as compile-time execution.
这似乎并没有真正向我强调模板元编程的优势......?
我问这个问题是因为我对模板元编程可以做什么来优化/提高低延迟 C++ 应用程序的效率很感兴趣。一路上我可能没有理解正确的地方,所以请随时纠正我的理解。
最佳答案
您是否阅读过无数深入讨论 TM 的文章?例如:
- http://www.codeproject.com/Articles/3743/A-gentle-introduction-to-Template-Metaprogramming
- http://aszt.inf.elte.hu/~gsd/halado_cpp/ch06s04.html
- http://blog.lorentey.hu/2010/04/21/cpp-template-metaprogramming/
- 等等等等
查看(一种)模板元编程的一种简单方法是“强”内存。一个常见的例子如下:
假设您的程序需要计算某个数字的阶乘。使用 TM,您可以在编译时计算阶乘,这会增加编译时间(和二进制大小)但会减少运行时间。示例代码来自上面的第二个站点;如果您以“幼稚”的方式进行操作,您的代码将如下所示:
int factorial( int n) {
return (n==0) ? 1 : n*factorial(n-1)l
}
int main() {
cout << factorial(5) << endl;
return 0;
}
使用 TM 我们可以在编译时计算阶乘:
// factorial.cpp
#include <iostream>
template <int N>
struct Factorial {
enum { value = N * Factorial<N-1>::value };
};
template <>
struct Factorial<1> {
enum { value = 1 };
};
// example use
int main() {
const int fact5 = Factorial<15>::value;
std::cout << fact5 << endl;
return 0;
}
在这里Factorial<15>::value
本质上是一个编译时常量。一如既往,简单的示例并不是特别有用,但希望您能理解其中的要点。
关于C++ 模板元编程- 不确定我是否大惊小怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15045112/