我想创建一个通用的向量类,并为一些情况创建特殊化。就像这样(它不能编译,但希望能够传达我的意图):
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]; }
};
换句话说,我希望元素的默认类型为
float
,并且在dim = 2
的情况下具有x()
和y()
访问器方法,在dim = 3
的情况下具有x()
、y()
和z()
。 我对错误消息有点困惑:
< p >(< code >T< / code >同样如此)。 请问怎样才能正确完成这个任务?(如果可能的话)vector.h:56:10: error: declaration of ‘int dim’
vector.h:6:10: error: shadows template parm ‘int dim’