mercredi 29 juin 2016

Why does the compiler complain about this not being a constexpr?

I am trying to learn a bit more about using constexpr in practice and created the following Matrix class template:

#include <array>
#include <vector>

template <typename T, int numrows, int numcols>
class Matrix{
public:
    using value_type = T;
    constexpr Matrix() : numrows_(numrows), numcols_(numcols){}
   ~Matrix(){}

    constexpr Matrix(const std::array<T, numrows*numcols>& a) :
        numrows_(numrows), numcols_(numcols),values_(a){}

    constexpr Matrix(const Matrix& other) :
        numrows_(other.numrows_), numcols_(other.numcols_), values_(other.values_){

    }

    constexpr const T& operator()(int row, int col) const {
        return values_[row*numcols_+col];
    }

    T& operator()(int row, int col){
        return values_[row*numcols_+col];
    }

    constexpr int rows() const {
        return numrows_;
    }

    constexpr int columns() const {
        return numcols_;
    }


private:
    int numrows_;
    int numcols_;
    std::array<T, numrows*numcols> values_{};
};

The idea is to have a simple Matrix class, which I can use for small matrices to evaluate Matrix expressions at compile time (note that that I have not yet added the usual Matrix operators such as additions and multiplication).

When I try to initialize a Matrix instance as follows:

constexpr std::array<double, 4> a = {1,1,1,1};
constexpr Matrix<double, 2, 2> m(a);

I am getting the following error from the compiler (MS Visual C++ 14):

error: C2127: 'm': illegal initialization of 'constexpr' entity with a non-constant expression

Note sure what I am doing wrong...any help to make this work would be greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire