Home > Net >  How to assign two dimensional initializer list in c ?
How to assign two dimensional initializer list in c ?

Time:05-10

I inherited my class from vector and I would like to be able to assign list to my class like to vector.

My code is as follows:

#include <vector>
using namespace std;

template<typename T>
class Matrix
    : public vector<vector<T>>
{
public:
    Matrix( vector<vector<T>> && m )
        : vector<vector<T>>( m )
    {}

    // Tried this approach, but it doesn't work
    // Matrix(std::initializer_list<std::initializer_list<T>> l){
    // }
}

int main()
{
  Matrix<int> m({{0, 1}, {2, 3}}); // it works
  // Matrix<int> m = {{0, 1}, {2, 3}}; // error: no instance of constructor "Matrix<T>::Matrix [with T=int]" matches the argument list -- argument types are: ({...}, {...})
}

CodePudding user response:

Just bring std::vector constructor to your class scope:

template <typename T> class Matrix : public vector<vector<T>> {
  public:
    using vector<vector<T>>::vector;
};

https://godbolt.org/z/b3bdx53d8

Offtopic: inheritance is bad solution for your case.

  • Related