2.4 常整數(shù)映射為型別
以下模板:
1 template < int v >
2 struct Int2Type{
3 enum { value = v };
4 }
Int2Type會根據(jù)引數(shù)所得的不同數(shù)值來產(chǎn)生不同型別。Int2Type<0> 和 Int2Type<1>是兩種不同的類型。采用Int2Type可根據(jù)編譯期計算出來的結果選用不同的函數(shù)。實際上你可以運用一個常數(shù)達到靜態(tài)分派功能。
一般而言,符合下列兩個條件可使用Int2Type:
a.有必要根據(jù)某個編譯期常數(shù)調(diào)用一個或數(shù)個不同的函數(shù)。
b.有必要在編譯期實施“分派”。
運行時分派可以使用if...else...或switch。但有時難以做到。舉例如下:
假設一個容器NiftyContainer,
1 template <class T> class NiftyContainer{};
其內(nèi)含指針,指向 T 的對象。為了復制容器中某個對象,你想調(diào)用copy構造函數(shù)(非多態(tài))或虛函數(shù)Clone()(多態(tài))。但你無法這樣做:
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 };
你會發(fā)現(xiàn)編譯不過,編譯器會發(fā)現(xiàn)未定義的函數(shù)。而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函數(shù)。