elad
elad

Reputation: 369

using a fixed size array in another array initialize list

I tried to do the following :

template <typename T, int N>
struct Vector {
  T v[N];
  template<typename... Args> Vector(Args... args) : v { args... } {}
  template<typename S> Vector(Vector<S, N> const & V) : v {V.v} {}
};
int main() {
  Vector<float, 4> V (1.0f, 2.0f, 3.0f, 4.0f);
  Vector<float, 4> V2 (V);
  for (auto f : V2.v) { cout << f << ", "; } cout << endl;
  return 0;
}

And it worked (printed "1, 2, 3, 4, "), so I did not suspect anything until I tried to "specialize it" with :

  Vector(Vector const & V) : v {V.v} {}

or to use it with :

  Vector<double, 4> V2 (V);

And the compiler said :

error: cannot convert 'const float*' to 'float' in initialization

or the same with 'double'.

After that I tried simple arrays, and it failed with the same error, yet with enough templating it works..

Can someone please explain to me what is going on here?

Upvotes: 0

Views: 355

Answers (1)

felix
felix

Reputation: 2222

You can't initialize an array with another array.

No, it doesn't working with template copy constructor either, the following code snippet just gives the same error message.

template <class T, int N>
struct Vector2 {
  T vv[N];
};

template <typename T, int N>
struct Vector {
  T v[N];
  template<typename T1>
  Vector(const Vector2<T1, N> & V) : v{V.vv} {}
};

int main() {
  Vector2<float, 4> V2;
  Vector<float, 4> V1(V2);

  return 0;
}

The reason why your code snippet works is because that the compiler used the implicitly declared copy constructor. If you explicitly declare it as deleted or as private member, you will find out that the compiler doesn't even try to instantiate the template copy constructor, which I don't know why.

And I find that the V.v always decays to pointer, even if I try to cast it to T (&)[N] with reinterpret_cast. *reinterpret_cast<T (*)[N]>(V.v)

So... I try to find out an answer but it just lead to more questions...


A workaround can be wrapping the array into a class.

Upvotes: 1

Related Questions