9

次の 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 が失敗します)。

$ 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 を表すクラスなど) を使用できるようにしたい...この振る舞いを取得しますか?

EDIT 1:static_assertクラスを削除すると、正常に動作します。

Matrix<std::complex<double>> m1(3,3);
m1.fill(std::complex<double>(1.,1.));
cout << m1 << endl;
4

2 に答える 2

15

arithmeticinはis_arithmetic誤称です。というか、C++ の名前です。英語での意味と同じ意味ではありません。組み込みの数値型 (int、float など) の 1 つであることを意味します。 std::complex組み込みではなく、クラスです。

本当にそれが必要ですstatic_assertか? ユーザーに任意のタイプで試してもらいませんか? タイプが必要な操作をサポートしていない場合は、運が悪いです。

于 2012-08-19T09:19:55.577 に答える
1

通常は「数値」とは見なされない型の行列を使用して、興味深いことができます。行列とベクトルは、実際には数値から多くの種類の「代数環」に一般化されます。基本的には、通常の + および * 操作が定義されているオブジェクトの任意のセットです。

したがって、ベクトルの行列、他の行列、複素数などを使用できます。加算、減算、および乗算演算子をサポートするクラスまたはプリミティブ型は、正しく機能します。演算子を正しく定義すると、暗黙のコンパイル爆弾が「matrix<std::string>」のようなほとんどの乱用をキャッチするはずです。

于 2013-08-12T21:34:36.573 に答える