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;
    };
    
  • 相关阅读:
    利用中转输出表制作HijackDll
    webshell查杀
    说说无线路由器后门的那些事儿(1)-D-Link篇
    htpwdScan — 一个简单的HTTP暴力破解、撞库攻击脚本
    OD消息断点
    Burp Suite详细使用教程-Intruder模块详3
    burp intruder模块详解
    谈谈神的能力
    语法入门基本概念
    多项式
  • 原文地址:https://www.cnblogs.com/zhcpku/p/15202871.html
Copyright © 2011-2022 走看看