模板元編程(英語:Template metaprogramming;縮寫:TMP)是一種元編程技術,編譯器使用模板產生暫時性的源碼,然後再和剩下的源碼混合並編譯。
這些模板的輸出包括編譯時期常數、數據結構以及完整的函數。如此利用模板可以被想成編譯期的運行。
2.模板元編程的優缺點
編譯期對運行期:因爲模板的運算以及展開都是在編譯期,這會花相對較長的編譯時間,但能夠獲得更有效率的運行碼。
這項編譯期花費一般都很小,但對於大項目或是普遍依賴模板的程序,也許會造成很大的編譯開銷。
泛型程序設計::模板元編程允許程序員專注在架構上並委託編譯器產生任何客戶碼要求的實現。因此,模板元編程可達成真正的泛用代碼,促使代碼縮小並較好維護。
可讀性:: 對於C++來說,模板元編程的語法及語言特性比起傳統的C++編程,較難以令人理解。因此對於那些在模板元編程經驗不豐的程序員來說,程序可能會變的難以維護。
移植性:: 對於C++來說,由於各編譯器的差異,大量依賴模板元編程(特別是最新形式的)的代碼可能會有移植性的問題。
3.實例:
/*
例子1:求階乘
*/
template<int n>
class Factorial
{
public:
enum {value = n * Factorial<n-1>::value };
};
template<>
class Factorial<0>
{
public:
enum {value = 1 };
};
/*
例子2:多態的實現
*/
template <class Derived>
struct base
{
void interface()
{
static_cast<Derived*>(this)->implementation();
}
};
struct derived1 : base<derived1>
{
void implementation()
{
cout << "in derived1" << endl;
}
};
struct derived2 : base<derived2>
{
void implementation()
{
cout << "in derived2" << endl;
}
};
test程序
#include "test.h"
int main()
{
cout << Factorial<4>::value << endl;
derived1 test1;
derived2 test2;
test1.interface();
test2.interface();
}