template <class T, T v>struct integral_constant;
1234567
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; } };
12345678
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() const noexcept { return v; } constexpr T operator()() const noexcept { return v; } };
1234567891011121314
// 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; }
120