模板元编程和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;
}
复制代码

 

posted @   花与不易  阅读(249)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示