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

8 c++ types complex-numbers

我创建了以下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;
};
Run Code Online (Sandbox Code Playgroud)

我试着使用std :: complex矩阵:

Matrix<std::complex<double>> m1(3,3);
Run Code Online (Sandbox Code Playgroud)

问题是编译失败(static_assert失败):

$ 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
Run Code Online (Sandbox Code Playgroud)

为什么std :: complex不是算术类型?我想启用无符号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;
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 14

arithmeticis_arithmetic是用词不当.或者更确切地说,它是一个C++ - nomer.它与英语中的含义并不相同.它只是意味着它是内置数值类型之一(int,float等). std::complex不是内置的,它是一个类.

你真的需要static_assert吗?为什么不让用户尝试任何类型?如果类型不支持所需的操作,那么运气不好.

  • 任何想要乘以std :: string矩阵的人都应该得到它们. (3认同)
  • @RM你为什么要强加这样的限制? (2认同)
  • @BenjaminLindley:"static_assert"的一个重要部分是为模板替换失败提供更可读和合法的错误消息,而不是巨大的模板实例化. (2认同)