..
integral_constant
定义 1
This template is designed to provide compile-time constants as types.
template <class T, T v>
struct integral_constant;
实现
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; }
};
应用: 编译器求值
// factorial as an integral_constant
#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;
}