C++模板元編程,是使用template進行編譯期運算的一種機制,可以認為是C++的一種編程方式。
第一個例子:計算整數N的階乘。
//模板的一般形式template<int N>class Factorial{public: enum { _result = N * Factorial<N-1>::_result };};//用於結束遞迴規則的特化模板template<>class Factorial<0>{public: enum { _result = 1 };};int main(){ const int Num = 10; cout << Num << "! = " << Factorial<Num>::_result << endl;}
運行結果:10! = 3628800
其中的思考方式,我感覺是數學歸納法的應用。注意模板在其中起的作用,在編譯期,編譯器使用template產生了class Factorial<0>……class Factorial<10>一共11個class定義,在程式運行時其實計算過程並沒有佔用CPU時間,只不過這麼多class的定義佔用了一些記憶體。
第二個例子:編譯期的if語句
這是 Bjarne Stroustrup在《Evolving a language in and for the real world C++ 1991-2006》一文中舉的例子。
struct T_Left{ int value;};struct T_Right{ char value;};template<bool b, class X, class Y>struct if_{ typedef X type; // use X if b is true};template<class X, class Y>struct if_<false, X, Y>{ typedef Y type; // use Y if b is false};int main(){ cout << "Type Size = " << sizeof(if_<sizeof(T_Left) < 4, T_Left, T_Right>::type) << endl;}
其實也是根據編譯期能確定的值,來進行編譯期的選擇。
模板元編程的應用程式套件括:Blitz++庫;boost::mpl庫;以及《Modern C++ Design》一書中提到的typelist。