C++ 模板元编程- 不确定我是否大惊小怪?

标签 c++ templates template-meta-programming

据我了解,正常的 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 的文章?例如:

查看(一种)模板元编程的一种简单方法是“强”内存。一个常见的例子如下:

假设您的程序需要计算某个数字的阶乘。使用 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/

相关文章:

c++ - 模板生成一百个C回调函数,编译不慢

C++ 在 LD_LIBRARY_PATH 上查找文件

c++ - 来自 openCV 的代码有什么作用?

c++ - 将表示小数的 int 转换为 double 的正确方法是什么

c++ - 在 C++ 中有条件地强制执行模板类型

常量数据持有者类的 C++ 模板

c++ - 为什么不接受使用概念的此类特化?

C++ 类不是自身的基础

c++ 模板类无法修复 ostream 和 istream 函数

当类模板 "*"包装在宏中时,C++ 的参数太少