I am trying to implement a generic template class. I would like the default element of the class to be instantiated with std::array of 3 ints {0,0,0} however, I don't know how to place the default list of arguments.
My goal:
Vec<> a;
-> creates a vec3 with an array {0,0,0} as private member
Vec<int,3> b;
-> the same as above
Vec<int,2> c;
-> creates a vec with array {0,0}
Vec<double,3> d(4,5,9);
-> creates a vec with {4,5,9} as doubles
My code,
vec.h
template<typename T = int, int N = 3>
class Vec{
public:
Vec(T v0,T v1) : vec_coordinates_ ({v0,v1} = {0,0}){
static_assert(N == 2, "wrong number of arguments");
};
Vec(T v0,T v1,T v2) : vec_coordinates_ ({v0,v1,v2}){
static_assert(N == 3, "wrong number of arguments");
};
private:
std::array<T,N> vec_coordinates_;
}
doesn't compile.
The constructor for an array with two elements works.
Vec(T v0,T v1) : vec_coordinates_ ({v0,v1} = {0,0}) {
static_assert(N == 2, "wrong number of arguments");};
The above compiles, however
Vec3(T v0,T v1,T v2) : vec_coordinates_ ({v0,v1,v2} = {0,0,0}) { //C2059
static_assert(N == 3, "wrong number of arguments");
};
does not compile. I get the error:
error C2059: syntax error: '='
on the line with {0,0,0}.
I don't understand the difference, why the {0,0} compiles and the array with 3 zeros doesn't. I would be very grateful for any tips or pieces of advice.
question from:
https://stackoverflow.com/questions/65920543/how-to-set-a-default-arguments-for-a-generic-template-class