我创建了以下 Matrix 类:
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;
};
我尝试使用 std::complex 的矩阵:
Matrix<std::complex<double>> m1(3,3);
问题是编译失败(static_assert fails):
$ 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
为什么 std::complex 不是算术类型?我想启用 unsigned int (N)、int (Z)、double (R)、std::complex (C) 和一些自制类(例如代表 Q 的类)...得到这个行为?
编辑 1: 如果我删除 static_assert
,类会正常工作。
Matrix<std::complex<double>> m1(3,3);
m1.fill(std::complex<double>(1.,1.));
cout << m1 << endl;
最佳答案
is_arithmetic
中的arithmetic
用词不当。或者更确切地说,它是一个 C++ 名词。它的意思与英语中的意思不同。它只是意味着它是内置数字类型之一(int、float 等)。 std::complex
不是内置的,它是一个类。
你真的需要那个static_assert
吗?为什么不让用户尝试使用任何类型呢?如果类型不支持所需的操作,那就倒霉了。
关于c++ - 为什么 std::complex 不是算术类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12025447/