• 【c++ templates读书笔记】【7】模板元编程


    模板实例化机制是一种基本的递归语言机制,可以用于在编译期执行复杂的计算。这种随着模板实例化所出现的编译器计算通常被称为template metaprogramming。

    例子一,计算阶乘:

    //Pow.h
    #ifndef POW_H
    #define POW_H
    
    template<int M,int N>
    class Pow{
    public:
    	enum { result = M*Pow<M, N - 1>::result };
    };
    template<int M>
    class Pow<M, 0>{
    public:
    	enum{ result = 1 };
    };
    
    #endif
    //main.cpp
    #include "Pow.h"
    #include<iostream>
    using namespace std;
    
    int main(){
    
    	cout << Pow<2,8>::result << endl;
    
    	system("pause");
    	return 0;
    }
    

    例子二,计算平方根:

    //Sqrt.h
    #ifndef SQRT_H
    #define SQRT_H
    
    template<int N, int LO = 0, int HI = N>
    class Sqrt{
    public:
    	enum { mid = (LO + HI + 1) / 2 };
    	enum { result = (N<mid*mid) ? Sqrt<N, LO, mid - 1>::result : Sqrt<N, mid, HI>::result };
    };
    template<int N, int M>
    class Sqrt<N, M, M>{
    public:
    	enum{ result = M };
    };
    
    #endif
    //main.cpp
    #include"Sqrt.h"
    #include<iostream>
    using namespace std;
    
    int main(){
    	cout << Sqrt<102>::result << endl;
    
    	system("pause");
    	return 0;
    }
    

    例子三,计算点乘:

    //DoProduct.h
    //基本模板
    template<int Dim,typename T>
    class DotProduct{
    public:
    	static T result(T* a, T* b){
    		return *a * *b + DotProduct<Dim - 1, T>::result(a + 1, b + 1);
    	}
    };
    //作为结束条件的局部特化
    template<typename T>
    class DotProduct<1,T>{
    public:
    	static T result(T* a, T* b){
    		return *a * *b;
    	}
    };
    //辅助函数
    template<int Dim,typename T>
    inline T dot_product(T* a, T* b){
    	return DotProduct<Dim, T>::result(a, b);
    }
    //main.cpp
    #include"DotProduct.h"
    #include<iostream>
    using namespace std;
    
    int main(){
    	int a[3] = { 1, 2, 3 };
    	int b[3] = { 4, 5, 6 };
    	cout << dot_product<3>(a, b) << endl;
    
    	system("pause");
    	return 0;
    }
    

    上述例子说明一个template metaprogram可以包含下面几部分:

    状态变量:也就是模板参数。

    迭代构造:通过递归。

    路径选择:通过使用条件表达式或者特化。

    整型(即枚举里面的值应该为整型)算法。

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    MySQL 多列索引优化小记
    Spring MVC + Security 4 初体验(Java配置版)
    Java程序通过代理访问网络
    Spring RESTful + Redis全注解实现恶意登录保护机制
    WinSCP 中普通用户以 root 身份登录 Linux
    Linux下修改系统时区
    Git如何检出指定目录或文件
    朴素贝叶斯
    console.log 被重写覆盖以后如何恢复
    MongoDB 基础命令使用学习记录
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4921339.html
Copyright © 2020-2023  润新知