mardi 14 janvier 2020

How to define a vector class using std::array with aggregate initialization?

I define a class like this

#include<array>
template<class T,size_t D> 
class vec{
    private:
        std::array<T,D> arr;
    public:
        vec(std::initializer_list<T> l) : arr(l){ }
};

Then I construct the object of this class like this.

vec<int,3> v = {1,2,3};

Then I get an error

main.cpp:5:26: error: cannot bind non-const lvalue reference of type ‘std::initializer_list<int>&’ to an rvalue of type ‘std::initializer_list<int>’
     vec<int,3> v = {1,2,3};
                          ^
In file included from main.cpp:1:
vec.hpp:12:9: note:   initializing argument 1 of ‘vec<T, D>::vec(std::initializer_list<_Tp>&) [with T = int; long unsigned int D = 3]’
         vec(std::initializer_list<T>& l) : arr(l){ }

I wonder how can I make the aggregated initialization in my constructor valid.

Aucun commentaire:

Enregistrer un commentaire