Home > Software design >  C template class specialization constructor
C template class specialization constructor

Time:09-04

I want to create a generic Vector class like this Vector<int Dimension, typename Type>. And this is my code:

template <int Dimension, typename Type>
class Vector
{
public:
  Vector() 
    : _data {} 
  {}
  Vector(const std::array<Type, Dimension>& init)
    : _data {init}
  {}
  ...
protected:
 std::array<Type, Dimension> _data;
};

With that declaration, i can initialize my vector with a std::array.

Vector<3, float> vec({1.0f, 2.0f, 3.0f});
// or like this
Vector<3, float> vec = {{1.0f, 2.0f, 3.0f}};

But now i want my vector has a better constructor for some common vector type like Vec1, Vec2, Vec3, ... I have tried to create a recursion template class to add an additional constructor for each of them:

template <typename Type>
class Vector<3, Type>
{
public:
  Vector(const Type& x, const Type& y, const Type& z)
    : _data {x, y, z}
  {}
};

But when i compile my program i received this error:

error C3861: '_data': identifier not found

My questtion are:

  • Why this error happen?
  • And how can i add an additional constructor for some common template of my Vector.

PS: Sorry if my English is hard to understand

  • Related