C++ 为什么std::complex不是算术类型?

C++ 为什么std::complex不是算术类型?,c++,types,complex-numbers,C++,Types,Complex Numbers,我创建了以下矩阵类: 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&am

我创建了以下矩阵类:

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;
};

中的
算术
是一个错误的名称。或者更确切地说,它是一个C++术语。它的意思和英语中的意思不一样。它只是意味着它是一种内置的数字类型(int、float等)
std::complex
不是内置的,它是一个类


你真的需要这个
静态断言
?为什么不让用户尝试使用任何类型?如果类型不支持所需的操作,那么就很倒霉。

对于通常不被视为“数字”的类型矩阵,您可以做一些有趣的事情。矩阵和向量实际上从数字推广到许多类型的“代数环”——基本上是定义了常用+和*运算的任何对象集

因此,可以有向量矩阵、其他矩阵、复数等。任何支持加法、减法和乘法运算符的类或基本类型都可以正常工作。
如果您正确定义了运算符,隐式编译炸弹应该会捕获大多数滥用,如“矩阵”。

出于好奇:如果删除
静态断言
,您能否实例化并使用
矩阵的实例?@MarcusRiemer Yes。它工作得很好。显然,实际上并不需要
静态断言。我用它来“清洁”代码并让我的矩阵仅用于数学…@R.M.你为什么要施加这样的限制?任何想将std::string矩阵相乘的人都应该得到他们应得的。@BenjaminLindley:
static\u assert
的很大一部分目的是为模板替换提供更具可读性和合法性的错误消息失败,而不是一个巨大的模板实例化喷涌而出。@BenjaminLindley,因为这个类是为数学而设计的。使用double*的矩阵,std::string,std::vector,std::exception。。。这是没有意义的。
Matrix<std::complex<double>> m1(3,3);
$ 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
Matrix<std::complex<double>> m1(3,3);
m1.fill(std::complex<double>(1.,1.));
cout << m1 << endl;