模板实例化机制是一种基本的递归语言机制,可以用于在编译期执行复杂的计算。这种随着模板实例化所出现的编译器计算通常被称为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可以包含下面几部分:
状态变量:也就是模板参数。
迭代构造:通过递归。
路径选择:通过使用条件表达式或者特化。
整型(即枚举里面的值应该为整型)算法。