混合部分模板特化和默认模板参数

Tam*_*lei 6 c++ templates template-specialization c++11

我想创建一个通用的矢量类,并为少数情况创建特化.像这样的东西(它不编译,但希望传达我的意图):

template<int dim, typename T = float>
class Vector
{
public:
    typedef Vector<dim, T> VecType;

    Vector() { /**/ }
    Vector(const VecType& other) { /**/ )
    Vector& operator=(const VecType& other) { /**/ }

    VecType operator+(const VecType& other) { /**/ }    
    VecType operator-(const VecType& other) { /**/ }    
    T operator*(const VecType& other) { /**/ }

private:
    std::array<T, dim> elements;
};

template<int dim, typename T>
class Vector<2>
{
public:
    T x() const { return elements[0]; }
    T y() const { return elements[1]; }
};

template<int dim, typename T>
class Vector<3>
{
public:
    T x() const { return elements[0]; }
    T y() const { return elements[1]; }
    T z() const { return elements[2]; }
};
Run Code Online (Sandbox Code Playgroud)

换句话说,我想要的元素的默认类型是float,我想拥有x()y()存取方法的dim = 2情况下,和x(),y()z()dim = 3案例.我对错误消息感到有些困惑:

vector.h:56:10:错误:'int dim'的声明

vector.h:6:10:错误:阴影模板parm'int dim'

(同样T).

我该怎么做才能正确?(如果它是可能的)

ken*_*ytm 10

1.

部分特化模板时,仅提供实际上是参数的模板参数.由于您已经固定dim为2或3,因此无需再次指定它.

template<typename T>
class Vector<2, T>
{
   ....
Run Code Online (Sandbox Code Playgroud)

2.

专业化课程实际上意味着改变整个声明.因此,通用的成员Vector<dim, T>将无法在专业中使用Vector<2, T>.您可以将泛型Vector<dim, T>作为内部基类,并创建一个仅用于特化的子类:

template<int dim, typename T>
class VectorImpl;

...

template<int dim, typename T = float>
class Vector : public VectorImpl<dim, T> {};

template<typename T>
class Vector<2, T> : public VectorImpl<2, T>
{
public:
   T x() const { ... }
};
Run Code Online (Sandbox Code Playgroud)

3.

你不需要定义VecType!在模板中,您可以使用Vector.它将自动推断出具有正确参数的类.

编译的最终结果:

#include <array>

template<int dim, typename T>
class VectorImpl
{
public:
    //typedef Vector<dim, T> VecType;

    VectorImpl() {  }
    VectorImpl(const VectorImpl& other) {  }
    VectorImpl& operator=(const VectorImpl& other) { return *this; }

    VectorImpl operator+(const VectorImpl& other) { return *this; }
    VectorImpl operator-(const VectorImpl& other) { return *this; }
    T operator*(const VectorImpl& other) { return 0; }

protected:
    std::array<T, dim> elements;
};

template <int dim, typename T = float>
class Vector : public VectorImpl<dim, T> {};

template<typename T>
class Vector<2, T> : public VectorImpl<2, T>
{
public:
    T x() const { return this->elements[0]; }
    T y() const { return this->elements[1]; }
};

template<typename T>
class Vector<3, T> : public VectorImpl<2, T>
{
public:
    T x() const { return this->elements[0]; }
    T y() const { return this->elements[1]; }
    T z() const { return this->elements[2]; }
};

int main()
{
    Vector<2> v;
    Vector<3> vv;
    v + v;
    vv.z();
}
Run Code Online (Sandbox Code Playgroud)