Why is std :: complex not an arithmetic type?

I created the following Matrix class:

template <typename T> class Matrix { static_assert(std::is_arithmetic<T>::value,""); public: Matrix(size_t n_rows, size_t n_cols); Matrix(size_t n_rows, size_t n_cols, const T& value); void fill(const T& value); size_t n_rows() const; size_t n_cols() const; void print(std::ostream& out) const; T& operator()(size_t row_index, size_t col_index); T operator()(size_t row_index, size_t col_index) const; bool operator==(const Matrix<T>& matrix) const; bool operator!=(const Matrix<T>& matrix) const; Matrix<T>& operator+=(const Matrix<T>& matrix); Matrix<T>& operator-=(const Matrix<T>& matrix); Matrix<T> operator+(const Matrix<T>& matrix) const; Matrix<T> operator-(const Matrix<T>& matrix) const; Matrix<T>& operator*=(const T& value); Matrix<T>& operator*=(const Matrix<T>& matrix); Matrix<T> operator*(const Matrix<T>& matrix) const; private: size_t rows; size_t cols; std::vector<T> data; }; 

I tried using the std :: complex matrix:

 Matrix<std::complex<double>> m1(3,3); 

The problem is that compilation fails (static_assert does not work):

 $ make g++-mp-4.7 -std=c++11 -c -o testMatrix.o testMatrix.cpp In file included from testMatrix.cpp:1:0: Matrix.h: In instantiation of 'class Matrix<std::complex<double> >': testMatrix.cpp:11:33: required from here Matrix.h:12:2: error: static assertion failed: make: *** [testMatrix.o] Error 1 

Why is std :: complex not an arithmetic type? I want to enable the use of unsigned int (N), int (Z), double (R), std :: complex (C) and maybe some home class (like a class representing Q) ... Is it possible to get this behavior?

EDIT 1: If I remove static_assert , the class is working fine.

 Matrix<std::complex<double>> m1(3,3); m1.fill(std::complex<double>(1.,1.)); cout << m1 << endl; 
+7
source share
2 answers

arithmetic in is_arithmetic is incorrect. Rather, it is a C ++ number. This does not mean the same as in English. It just means that it is one of the built-in numeric types (int, float, etc.). std::complex not built-in, it is a class.

Do you really need this static_assert ? Why not just let the user try it with any type? If the type does not support the necessary operations, then you are out of luck.

+13
source

You can do interesting things with type matrices that are usually not considered “numeric”. Matrices and vectors actually generalize from numbers to many kinds of “algebraic rings” - basically, any set of objects where the usual operations + and * are defined.

So, you can have vectors matrices, other matrices, complex numbers, etc. Then the correct classes or primitive types that support the operations of addition, subtraction and multiplication will be executed. If you define operators correctly, implicit compilation bombs should catch most of the abuses, such as "matrix <std :: string>".

0
source

All Articles