这是一个来自 wikipedia 的示例,它显示了 C++ 模板元编程:
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
我理解它是如何工作的,递归地使用 N 的模板参数值创建 Factorial 类型,直到找到特化 <0>,这允许编译器解析链上的值。
我的问题是:编译后会怎样?编译器最终会不会生成类似的东西:
int x = 24;
int y = 1;
还是结果会更复杂?我问是因为我想知道它是否基本上会导致:
Factorial<4>::value
被可执行代码中的常量 (24) 替换,或者如果它比这更复杂。我只是想弄清楚这如何提高已完成程序的效率,所以这会很有帮助:)