zoukankan      html  css  js  c++  java
  • C++ 编译期计算

    C++ 编译期计算

    模板元编程是个强大的工具,据说足以作为一门完备的语言了。这里只是简单记录一下,利用模板实现编译期计算的方式。

    sum([1,...n])

    #include <stdio.h>
    
    // 递推公式
    template<int n>
    class Sum {
    public:
        static const int value = n + Sum<n-1>::value;
    };
    
    // 边界值特化
    template <>
    class Sum<0> { // 注意 0 的位置
    public:
        static const int value = 0; // 注意全都是静态常量,才能保存到binary中const区
    };
    
    int main() {
        printf("%d
    ", Sum<100>::value);
    }
    

    斐波那契数列

    template <int num>
    class Fibonacci {
    public:
        static const int value = Fibonacci<num - 1>::value + Fibonacci<num - 2>::value;
    };
    
    template <>
    class Fibonacci<0> {
    public:
        static const int value = 0;
    };
    
    template <>
    class Fibonacci<1> {
    public:
        static const int value = 1;
    };
    

    组合数

    template <int n, int m>
    class Combinatorial {
    public:
        static const int value = Combinatorial<n - 1, m>::value + Combinatorial<n - 1, m - 1>::value;
    };
    
    template <int m>
    class Combinatorial<0, m> {
    public:
        static const int value = 0;
    };
    
    template <int n>
    class Combinatorial<n, 0> {
    public:
        static const int value = 1;
    };
    
    template <>
    class Combinatorial<0, 0> { // 可以同时匹配 <0,m> 和 <n,0> 的 <0,0> 需要特别给出
    public:
        static const int value = 1;
    };
    
  • 相关阅读:
    PV、UV、GMV
    保存Hive查询结果的方法 insert overwrite 用法
    Hive substr 函数截取字符串
    HIVE中join、semi join、outer join
    Hive 差集运算
    gitlab和github区别
    前端工程化 ESlint 配置
    ES6 WeakMap Map 区别
    js 创建数组方法以及区别
    eslint for...in 报错处理
  • 原文地址:https://www.cnblogs.com/zhcpku/p/15202871.html
Copyright © 2011-2022 走看看