0

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: ({...}, {...})
}
Andrey
  • 5,932
  • 3
  • 17
  • 35
  • The "error" line is not assignment, it's constructor syntax that looks like assignment. – Eljay May 09 '22 at 13:59
  • 2
    Try this: `Matrix m = {{{0, 1}, {2, 3}}};` For the gory details, obligatory [The Nightmare of Initialization in C++](https://www.youtube.com/watch?v=7DTlWPgX6zs) by Nicolai Josuttis. An hour long presentation on the initialization syntax pain point in C++. – Eljay May 09 '22 at 14:03
  • 2
    To expand on the comment by @Eljay, the first `{}` pair is for the `Matrix` class, the next `{}` pair is for the outer vector. And the innermost `{}` pairs is for the inner vectors. – Some programmer dude May 09 '22 at 14:05

1 Answers1

5

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.

Marek R
  • 32,568
  • 6
  • 55
  • 140
  • could you please advice the better approach? I need a matrix with dimensions unknown at compile time, and I want to multiply them (by overloading * operator). And I can not use other libraries (like eigen) – Andrey May 09 '22 at 14:17
  • @Andrey, instead of inheriting from the `vector` class, have a `vector` as a member of your Matrix. – ChrisMM May 09 '22 at 14:19
  • @ChrisMM Thanks, but in that case I have to use `.` to access matrix: like `myObject.mat` instead of just `myObject`. The last option looks better for me – Andrey May 09 '22 at 14:30
  • @Andrey, you should read [this](https://stackoverflow.com/questions/6806173/subclass-inherit-standard-containers) – ChrisMM May 09 '22 at 14:44