val
val

Reputation: 749

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.

Upvotes: 2

Views: 229

Answers (2)

Violet Giraffe
Violet Giraffe

Reputation: 33579

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});
}

Upvotes: 1

Jarod42
Jarod42

Reputation: 217145

You can use variadic template:

template <typename ... Ts>
Vector(Ts&&... args) : data{{std::forward<Ts>(args)...}}
{}

With potentially some SFINAE to restrict this constructor to good number of args, and args convertible to T.

Upvotes: 5

Related Questions