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: ({...}, {...}) } 
3
  • The "error" line is not assignment, it's constructor syntax that looks like assignment. Commented May 9, 2022 at 13:59
  • 2
    Try this: Matrix<int> m = {{{0, 1}, {2, 3}}}; For the gory details, obligatory The Nightmare of Initialization in C++ by Nicolai Josuttis. An hour long presentation on the initialization syntax pain point in C++. Commented May 9, 2022 at 14:03
  • 2
    To expand on the comment by @Eljay, the first {} pair is for the Matrix<int> class, the next {} pair is for the outer vector. And the innermost {} pairs is for the inner vectors. Commented May 9, 2022 at 14:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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, instead of inheriting from the vector class, have a vector as a member of your Matrix.
@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, you should read this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.