2.4 常整數映射為型別
以下模板:
1 template < int v >
2 struct Int2Type{
3 enum { value = v };
4 }
Int2Type會根據引數所得的不同數值來產生不同型別。Int2Type<0> 和 Int2Type<1>是兩種不同的類型。采用Int2Type可根據編譯期計算出來的結果選用不同的函數。實際上你可以運用一個常數達到靜態分派功能。
一般而言,符合下列兩個條件可使用Int2Type:
a.有必要根據某個編譯期常數調用一個或數個不同的函數。
b.有必要在編譯期實施“分派”。
運行時分派可以使用if...else...或switch。但有時難以做到。舉例如下:
假設一個容器NiftyContainer,
1 template <class T> class NiftyContainer{};
其內含指針,指向 T 的對象。為了復制容器中某個對象,你想調用copy構造函數(非多態)或虛函數Clone()(多態)。但你無法這樣做:
1 template < typename T, bool isPolymorphic>
2 class NiftyContainer{
3 void DoSomething(){
4 T* pSomeObj =
;
5 if (isPolymorphic){
6 T* pNewObj = pSomeObje->Clone();
7 //
8 }else{
9 T* pNewObj = new T(*pSomeObj);
10 //
11 }
12 };
你會發現編譯不過,編譯器會發現未定義的函數。而Int2Type提供了一個辦法:
1 template <typename T, bool isPolymrphoic>
2 class NiftyContainer{
3 private:
4 void DoSomething(T* pObj, Int2Type<true>){
5 T* pNewObj = pSomeObje->Clone();
6 //
7 }
8 void DoSomething(T* pObj, Int2Type<false>){
9 T* pNewObj = new T(*pSomeObj);
10 //
11 }
12 public:
13 void DoSomething(T* pObj){
14 DoSomething(pObj, Int2Type<isPolymorphoic>());
15 }
16 };
主要原因是編譯器不會去編譯一個未被用到的template函數。