模板實例化機制是一種基本的遞歸語言機制,可以用於在編譯期執行復雜的計算。這種隨着模板實例化所出現的編譯器計算通常被稱爲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可以包含下面幾部分:
狀態變量:也就是模板參數。
迭代構造:通過遞歸。
路徑選擇:通過使用條件表達式或者特化。
整型(即枚舉裏面的值應該爲整型)算法。