C++ 模板特定构造函数

C++ 模板特定构造函数,c++,windows-runtime,c++-cx,C++,Windows Runtime,C++ Cx,我正在写我自己的向量类,我遇到了一个问题。 我将我的类定义为模板,我对每个向量大小都有定义,并且我希望每个向量大小都有特定的构造函数。 代码如下: template<int size> ref class Vector { internal: Vector(int _x, int _y, int _z, int _w); private: float *m_data = new float[4]; }; 模板 参考类向量 { 内部: 向量(int x,i

我正在写我自己的向量类,我遇到了一个问题。 我将我的类定义为模板,我对每个向量大小都有定义,并且我希望每个向量大小都有特定的构造函数。 代码如下:

    template<int size>
ref class Vector
{
internal:

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

    float *m_data = new float[4];
};
模板
参考类向量
{
内部:
向量(int x,int y,int z,int w);
私人:
浮点*m_数据=新浮点[4];
};
定义如下:

using Vector2 = Vector<2>;
using Vector3 = Vector<3>;
using Vector4 = Vector<4>;
使用Vector2=Vector;
使用向量3=向量;
使用向量4=向量;

首先,我能做到吗?如果答案是“是”,如何操作?

如果您确实希望每个模板实例具有不同的行为,您可以这样做:

//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作为模板参数传递时的特定版本
模板
向量:向量(整数x,整数y,整数z,整数w)
{
//一些向量相关的东西
}
//Vector将使用默认版本
//当2作为模板参数传递时的特定版本
模板
向量:向量(整数x,整数y,整数z,整数w)
{
//一些向量相关的东西
}

如果需要公共接口,请将构造函数定义为具有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'
{
}
然后您可以这样使用它:

Vector<1> v_1(2);
Vector<2> v_2(4, 6);
//etc...
向量v_1(2); 向量v_2(4,6); //等等。。。
另外,第二个解决方案将允许向量的客户端仅针对您明确允许的
大小
进行实例化。

使用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);
}
模板
类向量
{
公众:
模板
显式向量(Ts…args):m_数据{static_cast(args)…}{
私人:
浮点m_数据[大小];
};
使用向量2=向量;
使用向量3=向量;
使用向量4=向量;
int main()
{
矢量2v2(42,5);
向量3v3(42,5,3);
向量4v4(42,5,51,69);
}

你的类
向量
向量
完全无关,它们是不同的类型。对于每个模板实例化,都定义了一个构造函数,所以您可以。可能您还想做其他事情,因为我没有看到您在任何地方使用
大小。如果是这样,请澄清问题。谢谢你的回答,我得到了答案。
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);
}