我很难理解以下模板定义和模板专门化定义是如何工作的?对我来说,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发布于 2012-02-01 23:04:36
这是一个模板元编程的例子。这个程序在编译时使用递归计算阶乘。递归的基础是:
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位整数。
发布于 2012-02-01 23:09:03
这不是一个真正的问题,而是一个声明。模板参数不一定是类型,但它们在绝大多数情况下都是类型,所以您可能以前没有见过非类型的模板参数。
也就是说,factorial<1>使用特殊化(使用value=1),而N>1的factorial<N>使用一般情况,即factorial<N-1>。这为您提供了阶乘的编译时评估(因为模板是递归扩展的)。
但是你知道34的阶乘有多大吗?你希望它适合一个整数吗?(答案: 295232799039604140847618609643520000000,否)。
https://stackoverflow.com/questions/9098061
复制相似问题