我正在努力理解模板定义。我的基本理解是模板定义允许将数据类型作为返回或参数作为通用类型。也就是说,模板参数是编译器在编译时实例化和链接的数据类型,
但我无法理解如下的复杂定义:
#include <iostream>
#include <type_traits>
template <unsigned n>
struct factorial : std::integral_constant<int,n * factorial<n-1>::value> {};
template <>
struct factorial<0> : std::integral_constant<int,1> {};
int main() {
std::cout << factorial<5>::value; // constexpr (no calculations on runtime)
return 0;
}
在哪里
template <class T, T v>
struct integral_constant {
static constexpr T value = v;
typedef T value_type;
typedef integral_constant<T,v> type;
constexpr operator T() { return v; }
};
输出:
120
很难想象模板是如何被实例化的:
template <int,5 * factorial<5-1>::value>
struct integral_constant {
static constexpr int value = 5 * factorial<5-1>::value;
typedef int value_type;
typedef integral_constant<5 * factorial<5-1>::value> type;
constexpr operator int() { return 5 * factorial<5-1>::value; }
};