2015-05-06 99 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); 
}