【问题标题】:Template specific constructor模板特定的构造函数
【发布时间】:2015-05-06 23:22:16
【问题描述】:

我正在编写自己的矢量类,但遇到了问题。 我将我的类定义为模板,我对每个向量大小都有定义,并且我想要每个向量大小的特定构造函数。 这是代码:

    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>;

首先我可以这样做吗?如果答案是肯定的怎么办?

【问题讨论】:

  • 你的班级Vector&lt;2&gt;Vector&lt;3&gt;完全无关,它们是不同的类型。对于每个模板实例化,都定义了一个构造函数,所以你没问题。可能您想做其他事情,因为我没有看到您在任何地方使用size。如果是这样,请澄清问题。
  • 感谢您的回复,我得到了答案。

标签: c++ windows-runtime c++-cx


【解决方案1】:

如果您想要通用接口,请将构造函数定义为具有 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...

另外,第二种解决方案将允许您的向量的客户端仅针对您明确允许的 sizes 实例化它。

【讨论】:

    【解决方案2】:

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

    //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
    }
    

    【讨论】:

      【解决方案3】:

      使用 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);
      }
      

      【讨论】:

        猜你喜欢
        • 2011-09-15
        • 1970-01-01
        • 2011-05-08
        • 1970-01-01
        • 2016-12-04
        • 2011-02-09
        • 1970-01-01
        • 2010-12-26
        • 1970-01-01
        相关资源
        最近更新 更多