阶乘 T - 1 的含义在模板定义中 [英] meaning of factorial<T - 1> in template definition
问题描述
我很难理解以下模板定义和模板特化定义是如何工作的?对我来说,factorial<34>
或 factorial
看起来很奇怪!
例如:
factorial::value
什么意思?
#include 模板结构阶乘{enum { value = factorial::value * T };};模板<>结构阶乘 1{枚举 { 值 = 1 };};int main(){std::cout <<阶乘<34>::值<’实例化testSTL01.cpp:5:3:从‘factorial<15>’实例化testSTL01.cpp:5:3:从‘factorial<16>’实例化testSTL01.cpp:5:3:从‘factorial<17>’实例化testSTL01.cpp:5:3:从‘factorial<18>’实例化testSTL01.cpp:5:3: [跳过 11 个实例化上下文]testSTL01.cpp:5:3:从‘factorial<30>’实例化testSTL01.cpp:5:3:从‘factorial<31>’实例化testSTL01.cpp:5:3:从‘factorial<32>’实例化testSTL01.cpp:5:3:从‘factorial<33>’实例化testSTL01.cpp:5:3:从‘factorial<34>’实例化testSTL01.cpp:15:29:从这里实例化testSTL01.cpp:5:3:警告:表达式中的整数溢出开始运行应用程序...0
这是模板元编程的示例.该程序在编译时使用递归计算阶乘.递归的基础在这里:
模板<>结构阶乘 1{枚举 { 值 = 1 };};
它说 1 的阶乘是 1.
另一个模板简单地说,一个数的阶乘是这个数乘以阶乘减 1.
template结构阶乘{enum { value = factorial::value * T };};
由于真的没有经典意义上的调用",模板实例化自身,模板参数等于编译时计算的 T-1
.>
附言警告显示 34 的阶乘溢出 32 位整数.
I have difficulties to understand how the following template definition and template specialization definition work? To me, factorial<34>
or factorial<T-1>
look strange!
For example:
factorial<T - 1>::value
means what?
#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
This is an example of template metaprogramming. This program calculates factorial at compile time using recursion. The base of recursion is here:
template<>
struct factorial<1> {
enum { value = 1 };
};
It says that factorial of 1 is 1.
The other template simply says that factorial of a number is that number times factorial minus 1.
template<int T>
struct factorial {
enum { value = factorial<T - 1>::value * T };
};
Since there is really no "calling" in the classic sense, the template instantiates itself with a template argument equal to T-1
calculated at compile time.
P.S. The warning shows that factorial of 34 overflows 32-bit integer.
这篇关于阶乘 T - 1 的含义在模板定义中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!