I am trying to learn a bit more on how to use C++ constant expressions in practice and created the following Matrix class template for illustration purposes:
#include <array> template <typename T, int numrows, int numcols> class Matrix{ public: using value_type = T; constexpr Matrix() : {} ~Matrix(){} constexpr Matrix(const std::array<T, numrows*numcols>& a) : values_(a){} constexpr Matrix(const Matrix& other) : 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: 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 I have not yet implemented the usual Matrix operators for addition 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!
std::arraydoesn't have a constexpr copy constructor?numrows_andnumcols_as member variables. Since you have the values as template parameters already, just return those.