模板实例化机制是一种基本的递归语言机制,能够用于在编译期执行复杂的计算。这种随着模板实例化所出现的编译器计算一般被称为template metaprogramming。ios
例子一,计算阶乘:算法
//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; }
例子三,计算点乘:spa
//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能够包含下面几部分:code
状态变量:也就是模板参数。递归
迭代构造:经过递归。编译器
路径选择:经过使用条件表达式或者特化。io
整型(即枚举里面的值应该为整型)算法。编译
版权声明:本文为博主原创文章,未经博主容许不得转载。模板