模板定义中阶乘<T - 1>的含义
meaning of factorial<T - 1> in template definition
我很难理解以下模板定义和模板专业化定义是如何工作的?对我来说,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,否)。
相关文章:
- 在 C++ 中的数组上使用阶乘函数
- 阶乘问题在 c++ 中给出错误的输出
- 大数的阶乘给出错误的输出
- 什么模板用法在阶乘中更好
- 为什么我在C++阶乘函数中出现编译错误?
- 计算阶乘的 C++17 倍表达式中的错误
- 为什么 Lisp 中 1000 阶乘的计算如此之快(并显示正确的结果)?
- 在C++中执行 N 阶乘编译时间的 3 种不同/相同方法
- 平方模型为零,阶乘模型问题
- 阶乘元规划
- 阶乘-c++ 我想以不同的方式打印
- 阶乘函数只返回C++中输入的答案
- 阶乘使用循环递增给出垃圾值
- 大 n 表示阶乘
- 为什么我不能在非常量表达式上使用此模板阶乘函数?
- 计算最大数字的阶乘
- 这个阶乘程序内部发生了什么?
- 返回阶乘C++的递归函数
- C++ 中是否有任何内置阶乘函数?
- 高效计算阶乘