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

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

我尝试使用 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/

相关文章:

c++ - inner_product 和复 vector

C++ 指针算术循环访问冲突

Haskell:有时返回函数的函数

java - double 也是一种 float 吗?

c - 试图除以复数,除以零

c++ - 将复数的 valarray 乘以标量

c++ - 无法使用 'designFlags' 类型的右值初始化 'int' 类型的变量

c++ - 给定一个二叉搜索树和一个数字,找到一条路径,其节点的数据相加为给定的数字。

c++ - 访问类私有(private)成员中的结构成员?

haskell - 函数无法匹配类型