模板元编程和constexpr的关系
使用模板特化来实现模板编程的递归。
#include <iostream>
#include <cstdint>
template<uint64_t N>
struct Fact
{
enum { Value = N * Fact<N - 1>::Value } ;
//enum需要在编译期的时候求值
};
template<>
struct Fact<1>
{
enum { value = 1};
};
//下面是使用constexpr作用于函数,让函数在编译期的时候执行
//是一个内联函数
//如果这是一个fib数列计算,需要计算的值太大的时候编译器就会报错
constexpr auto fact(uint64_t n)
{
if(n == 1) return n;
return n*fact(n - 1);
}
int main() {
constexpr auto value = fact(10); auto value = Fact<26>::Value; return 0; #include <iostream>
#include <cstdint> template<uint64_t N> struct Fib { enum { Value = Fib<N - 1>::Value + Fib<N - 2>::Value } ; //enum需要在编译期的时候求值
//c++11可以写成
static constexpr uint64_t value = Fib<N - 1>::value + Fib<N - 2>::value
};
template<>
struct Fib<1>
{
enum { value = 1};
};
template<>
struct Fib<2>
{
enum { value = 1};
};
int main()
{
auto value = Fib<26>::Value;
return 0;
}
#include <iostream>
#include <cstdint>
template <uint64_t base, uint64_t exp>
struct pow
{
enum { Value = base * pow<base, exp - 1>::Value };
};
template <uint64_t base>
struct pow<base, 1>
{
enum { Value = base };
};
int main()
{
auto value = pow<2, 10>::Value;
return 0;
}