模板定义中阶乘<T - 1>的含义

meaning of factorial<T - 1> in template definition

本文关键字:gt 阶乘 lt 定义      更新时间:2023-10-16

我很难理解以下模板定义和模板专业化定义是如何工作的?对我来说,factorial<34>factorial<T-1>看起来很奇怪!

例如:

factorial<T - 1>::value

意思是什么?

#include <iostream>
template<int T>
struct factorial {
  enum { value = factorial<T - 1>::value * T };
};
template<>
struct factorial<1> {
  enum { value = 1 };
};
int main()
{
  std::cout << factorial<34>::value << std::endl;
}    
g++ -o testSTL01 testSTL01.cpp -Wall
testSTL01.cpp: In instantiation of ‘factorial<13>’:
testSTL01.cpp:5:3:   instantiated from ‘factorial<14>’
testSTL01.cpp:5:3:   instantiated from ‘factorial<15>’
testSTL01.cpp:5:3:   instantiated from ‘factorial<16>’
testSTL01.cpp:5:3:   instantiated from ‘factorial<17>’
testSTL01.cpp:5:3:   instantiated from ‘factorial<18>’
testSTL01.cpp:5:3:   [ skipping 11 instantiation contexts ]
testSTL01.cpp:5:3:   instantiated from ‘factorial<30>’
testSTL01.cpp:5:3:   instantiated from ‘factorial<31>’
testSTL01.cpp:5:3:   instantiated from ‘factorial<32>’
testSTL01.cpp:5:3:   instantiated from ‘factorial<33>’
testSTL01.cpp:5:3:   instantiated from ‘factorial<34>’
testSTL01.cpp:15:29:   instantiated from here
testSTL01.cpp:5:3: warning: integer overflow in expression
start to run the app ...
0

这是一个模板元编程的例子。该程序在编译时使用递归计算阶乘。递归的基础在这里:

template<>
struct factorial<1> {
  enum { value = 1 };
};

它说1的阶乘是1。

另一个模板简单地说,一个数字的阶乘是这个数字乘以阶乘减1。

template<int T>
struct factorial {
  enum { value = factorial<T - 1>::value * T };
};

由于实际上没有经典意义上的"调用",模板用编译时计算的等于T-1的模板参数实例化本身。

附言:警告显示34的阶乘溢出32位整数。

这不是一个真正的问题,而是一句话。模板参数不具有为类型,但在绝大多数情况下,它们都是类型,因此您以前可能没有见过非类型模板参数。

也就是说,factorial<1>使用特殊化(与value=1一起),而N>1的factorial<N>使用一般情况,即factorial<N-1>。这为您提供了阶乘的编译时评估(因为模板是递归扩展的)。

但是你知道34的阶乘有多大吗?你希望它适合一个整数吗?(答案:2952327990396604140847618609643520000000,否)。