1

我很难理解以下模板定义和模板专业化定义是如何工作的?对我来说,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
4

2 回答 2

6

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

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

它说 1 的阶乘是 1。

另一个模板只是说一个数字的阶乘是该数字乘以阶乘减去 1。

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

由于实际上没有经典意义上的“调用”,因此模板使用等于在编译时计算的模板参数实例化自己。T-1

PS 警告显示 34 的阶乘溢出 32 位整数。

于 2012-02-01T15:04:36.033 回答
5

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

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

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

于 2012-02-01T15:09:02.743 回答