I would like to create a generic vector class and create specializations for a few cases. Something like this (it does not compile, but hopefully communicates my intentions):
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]; }
};
In other words, I want the default type of the elements to be float
and I want to have x()
and y()
accessor methods for the dim = 2
case, and x()
, y()
and z()
for the dim = 3
case. I'm a little confused by the error messages:
vector.h:56:10: error: declaration of ‘int dim’
vector.h:6:10: error: shadows template parm ‘int dim’
(same for T
).
How can I do this correctly? (if it's possible)