Search code examples
c++arraysmatrixinitializer-list

How do you pass fixed sized initializer lists of initializer lists through function parameters in C++?


I am making a matrix class where I want users to be able to instantiate the matrix like so:

Matrix<float, 2, 2> mat = { { 10, 20 }, { 30, 40 } };

My Matrix class is defined like so:

template<typename T, unsigned int ROWS, unsigned int COLS>
class Matrix
{
public:
    Matrix(std::array<std::array<T, ROWS>, COLS> matrix)
    {
        // ...
    }
    // ...
};

However, when I try instantiating the matrix, as I did above, I get "could not convert" errors from the compiler. I don't want to use initializer lists because I want compile-time errors to be triggered if the user defines the matrix with the wrong order. Does anyone why this isn't working? and if so is there an alternative?


Solution

  • This seems to work...

    template<typename T, unsigned int ROWS, unsigned int COLS>
    class Matrix
    {
    public:
        Matrix(const std::array<T, ROWS> (&matrix)[COLS]) {
            // ... 
        }
    };
    
    int main() {
        Matrix<float, 2, 2> mat = {{ { 10, 20 }, { 40, 40 } }};
    }
    

    Though the error message is quite bad when it fails, and it only fails if you provide too many rows or columns!... for the same reason that std::array<int,3> a = {1,2}; is valid...

    Edit:

    Matrix(const T (&matrix)[COLS][ROWS]) {}
    

    is also valid