val val - 2 months ago 7
C++ Question

Constructor of a templated vector(math kind)

For a small software renderer project I want to work on I'd need different types of vectors so I thought I'd template them up.

template<typename T, size_t dim> struct Vector {
std::array<T, dim> data;

Vector(){
data = { 0 };
}
}


This works nice with empty vectors like:

Vector<int, 3> v;


But how can I create a constructor that would accept a sytax like this:

Vector<int, 3> v(1, 2, 3);


Thought an std::initializer_list could work like this:

Vector(std::initializer_list<T> values){
data = values;
}
Vector<int, 3> v({1, 2, 3});


But the compiler says there's no acceptable conversion between
std::array
and
std::initializer_list
and the
({1, 2, 3})
syntax looks kinda clunky too.

Answer

It won't work with std::initializer_list, but it will with std::array proxy:

#include <array>
#include <iostream>

template<typename T, size_t dim> struct Vector {
  std::array<T, dim> data;

  Vector(){
    data = { 0 };
  }

  Vector(std::array<T, dim> initial_values) : data(initial_values) {}

};

int main() {
    Vector<int, 3> v({1, 2, 3});
}