zoukankan      html  css  js  c++  java
  • 模板元的简单学习

    特别值得注意的是,由于C++的模板语言是在编译器编译的时候完毕的,所以又称为静态语言,通常的C++语言又称为动态语言或者执行时语言。正是由于模板语言是在编译期完毕的。所以我们能够借助于这样的编译期的计算实现代码自己主动生成的目的,从而实现C++自己主动化编程。

    编译期
    typedef影射
    static类型变量和函数
    const 类型变量
    =:?-运算符
    enum
    执行期 对象使用
    函数调用
    变量赋值
    操作变量时&,+=,++,--等运算符。

    所以。假设想实现模板元编程。必需要把握的是一定要在编译期完毕程序,而不是在程序的执行期。细致区分执行期和编译期是模板元编程的第一步。

    #include <iostream>
    
    //编译期四则计算的演示样例代码
    template<size_t i,size_t j> struct Add { enum{value = i+j}; };
    template<size_t i,size_t j> struct Sub { enum{value = i-j}; };
    template<size_t i,size_t j> struct Mul { enum{value = i*j}; };
    template<size_t i,size_t j> struct Div { enum{value = i/j}; };
    int main()
    {
            std::cout << "4+2=" << Add<4,2>::value << std::endl;
            std::cout << "4-2=" << Sub<4,2>::value << std::endl;
            std::cout << "4*2=" << Mul<4,2>::value << std::endl;
            std::cout << "4/2=" << Div<4,2>::value << std::endl;
            //为了证明上面的计算是在编译期进行的,我们编写以下的代码測试
            //将模板值作为数组定义时使用的參数就能够证明是在编译期执行的计算:)
            int a[Add<4,2>::value];//这么定义并没有错
            int b[Sub<4,2>::value];//这么定义并没有错
            int c[Mul<4,2>::value];//这么定义并没有错
            int d[Div<4,2>::value];//这么定义并没有错
            std::cout << sizeof(a)/sizeof(int) << std::endl;
            std::cout << sizeof(b)/sizeof(int) << std::endl;
            std::cout << sizeof(c)/sizeof(int) << std::endl;
            std::cout << sizeof(d)/sizeof(int) << std::endl;
            return 0;
    }

    执行结果:


    2 利用模板元实现递归和循环

    #include <iostream>
    
    using namespace std;
    
    //求阶乘
    template<int N> struct power{
    	enum {value = N * power<N - 1>::value};//循环递归过程
    };
    template<> struct power<0>{
    	enum { value = 1} ;   //0的阶乘是1,也是循环的终止条件
    };
    
    //求和
    template<unsigned int N>struct sum{
    	enum{value = N + sum< N - 1 >::value};
    };
    
    template<> struct sum<1>{
    	enum{value = 1};
    
    };
    
    void main(){
    	int a[power<2>::value];
    	cout<<sizeof(a) / sizeof(int)<<" ";
    
    	int b[sum<3>::value];
    	cout<<sizeof(b) / sizeof(int)<<" ";
    }

    执行结果:


    參考文章:

    http://blog.csdn.net/pandaxcl/article/details/665409

    http://blog.csdn.net/ugg/article/details/2703326


  • 相关阅读:
    ELK
    alerta 集中化告警信息 -zabbix
    Python安装第三方模块出错 No module named setuptools
    Centos7 搭建bind9.9
    DNS 处理模块 dnspython
    varnish 项目实战
    中文版Postman测试需要登陆才能访问的接口(基于Cookie)
    fireFox模拟 post请求、上传插件,火狐浏览器中文postman插件
    MySQL单表最大记录数不能超过多少?
    ApiPost(中文版postman)如何发送一个随机数或者时间戳?
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5086614.html
Copyright © 2011-2022 走看看