2015-05-06 100 views
0

我正在編寫自己的矢量類,並且遇到了問題。 我將我的類定義爲模板,我定義了每個矢量大小,並且我想爲每個矢量大小指定特定的構造函數。 這裏是代碼:特定於模板的構造函數

template<int size> 
ref class Vector 
{ 
internal: 

    Vector(int _x, int _y, int _z, int _w); 
private: 

    float *m_data = new float[4]; 
}; 

和定義是:

using Vector2 = Vector<2>; 
using Vector3 = Vector<3>; 
using Vector4 = Vector<4>; 

首先,我能做到這一點?如果答案是肯定的,怎麼樣?

+0

你的類'矢量<2>'是完全無關的矢量''<3>,他們是不同類型的。對於每個模板實例化,都正在定義一個構造函數,所以你沒問題。可能你想做別的事情,因爲我沒有看到你在任何地方使用'size'。如果是這樣,請澄清問題。 – vsoftco

+0

感謝回覆我得到了我的答案。 – user3877301

回答

0

如果你想通用接口,定義構造函數有4個參數,並專注了。在內部,僅初始化這些成員,這是有效的,這種規模的載體:

template <> 
Vector<1>::Vector(int _x, int _y, int _z, int _w) 
: x(_x) //1D vector has only 'x' 
{ 
} 

template <> 
Vector<2>::Vector(int _x, int _y, int _z, int _w) 
: x(_x) 
, y(_y) //2D vector has 'x' and 'y' 
{ 
} 

等。但是這是醜陋的,迫使你你做一些事情「共同」,例如,你將持有甚至4組件2D vector 。有解決方法(用作成員變量的模板化結構,專門針對每個大小的向量),但這非常複雜。由於不同大小的矢量實際上不同類型,我會去滿級的專業化:

template<int size> 
class Vector; 

template<> 
class Vector<1> 
{ 
protected: 
    int x; 

public: 
    Vector(int _x) 
    : x(_x) 
    { } 

    //other members 
}; 

template<> 
class Vector<2> 
{ 
protected: 
    int x, y; 

public: 
    Vector(int _x, int _y) 
    : x(_x) 
    , y(_y) 
    { } 

    //other members 
}; 

然後你就可以使用這種方式:

Vector<1> v_1(2); 
Vector<2> v_2(4, 6); 
//etc... 

此外,第二個解決方案將允許客戶端你的矢量實例化它只爲那些size s,你明確允許。

+0

是的,我認爲你是對的我去這個方法。 – user3877301

0

如果你真的想爲每個模板實例不同的行爲,你可以做到這一點,像這樣:

//specific version for when 0 is passed as the template argument 
template<> 
Vector<0>::Vector (int _x, int _y, int _z, int _w) 
{ 
    //some Vector<0> related stuff 
} 

//Vector<1> will use the default version 

//specific version for when 2 is passed as the template argument 
template<> 
Vector<2>::Vector (int _x, int _y, int _z, int _w) 
{ 
    //some Vector<2> related stuff 
} 
0

用C++ 11,你可以這樣做:

template<int size> 
class Vector 
{ 
public: 

    template <typename ...Ts, 
       typename = typename std::enable_if<size == sizeof...(Ts)>::type> 
    explicit Vector(Ts... args) : m_data{static_cast<float>(args)...} {} 
private: 
    float m_data[size]; 
}; 

using Vector2 = Vector<2>; 
using Vector3 = Vector<3>; 
using Vector4 = Vector<4>; 

int main() 
{ 
    Vector2 v2(42, 5); 
    Vector3 v3(42, 5, 3); 
    Vector4 v4(42, 5, 51, 69); 
}