2012-02-13 65 views
2

相關:預處理指令#if和非類型模板參數

我能做到這一點?

template <int N> union Vector 
{ 
    float e[ N ] ; 
    // If N is 3, define x,y,z components 
    #if N==3 
    struct { float x,y,z ; } ; 
    #elif N==2 
    struct { float x,y ; } ; 
    #endif 
} ; 

// use 
int main() 
{ 
    Vector<2> xy ; 
    xy.e[ 0 ] = 5 ; 
    xy.e[ 1 ] = 2 ; 
    xy.x = 2 ; 

    Vector<3> xyz ; 
    xyz.z = 4 ; 
} 

回答

6

這個確切的代碼將不起作用,因爲宏替換髮生在模板實例化之前。換句話說,在編譯器實際上將開始用參數N實例化模板時,預處理器已經完成了它的條件包含。而且,預處理器沒有關於模板是什麼的語義概念,或者N是模板參數 - 它只將N視爲預處理器標記。

如果你想獲得這種效果,你可以使用模板特:

template <int N> union Vector 
{ 
    float e[ N ] ; 
}; 

template <> union Vector<3> 
    float e[ 3 ] ; 
    float x, y, z; 
} ; 

template <> union Vector<2> 
    float e[ 2 ] ; 
    float x, y; 
} ; 

希望這有助於!

+0

Livin'達到該userid,呃:) – bobobobo 2012-02-13 18:06:34

5

否在處理模板之前運行協處理器。改爲使用模板專業化。

template<int N> union Vector { 
    float e[N]; 
}; 

template<> union Vector<3> { 
    float e[3]; 
    struct { float x, y, z; }; 
}; 

// etc