使用模板表达式模式和继承编译错误(C ++)

时间:2014-11-14 21:30:39

标签: c++ templates inheritance gcc visual-studio-2013

在C ++中有一个Matrix实现,它遵循模板表达式模式。 我必须实现几种类型的操作,例如加法,乘法等。所以我决定使用纯虚拟运算符()创建一个基础MatrixOperation模板类,它将执行操作的实际技巧。 Matrix类有一个重载的 operator = 用于在分配中进行所有计算,并且它对Operation的运算符(i,j)进行分类。

事实是,在 Visual Studio 201 3中,这很好用,但不幸的是我必须用gcc测试它。你可以猜到, gcc 不喜欢我的解决方案。

为清楚起见,这是代码:

template<class T, int N, int M>
class my_matrix {
    T data[N][M];
public:
    my_matrix() {}

    template<class Left, class Right>
    my_matrix<T, N, M>& operator=(const MatrixOperation<T, N, M, Left, Right>& right) { 
        for (int i = 0; i < N; ++i)
            for (int j = 0; j < M; ++j) 
                data[i][j] = right(i, j);
        return *this;
    }

    const T& operator()(int n, int m) const { return data[n][m];  }
    T& operator()(int n, int m) { return data[n][m]; }
};

/** MatrixOperation base class*/
template <class T, int N, int M, class Left, class Right>
class MatrixOperation {
protected:
    const Left& left;
    const Right& right;
public:
    MatrixOperation(const Left& lhs, const Right& rhs) : left(lhs), right(rhs) {}
    virtual T operator()(int n, int m) const = 0;
};

/** MatrixSum class */
template <class T, int N, int M, class Left, class Right>
class MatrixSum : public MatrixOperation<T, N, M, Left, Right> {
public:
    MatrixSum(const Left& lhs, const Right& rhs) : MatrixOperation<T, N, M, Left, Right>(lhs, rhs) {}
    T operator()(int n, int m) const { return left(n, m) + right(n, m); }
};

gcc的答案是什么?这样的事情,只是更长时间,所有其他操作重复此错误。

g++ -Wall -c "Matrix.cpp"
Matrix.cpp: In member function ‘T MatrixSum<T, N, M, Left, Right>::operator()(int, int) const’:
Matrix.cpp:87:53: error: invalid initialization of reference of type ‘std::ios_base&’ from expression of type ‘int’
  T operator()(int n, int m) const { return left(n, m) + right(n, m); }
                                                     ^
In file included from /usr/include/c++/4.8/ios:42:0,
                 from /usr/include/c++/4.8/ostream:38,
                 from /usr/include/c++/4.8/iostream:39,
                 from Matrix.cpp:5:
/usr/include/c++/4.8/bits/ios_base.h:916:3: error: in passing argument 1 of ‘std::ios_base& std::left(std::ios_base&)’
   left(ios_base& __base)
   ^
Matrix.cpp:87:67: error: invalid initialization of reference of type ‘std::ios_base&’ from expression of type ‘int’
  T operator()(int n, int m) const { return left(n, m) + right(n, m); }
                                                                   ^
In file included from /usr/include/c++/4.8/ios:42:0,
                 from /usr/include/c++/4.8/ostream:38,
                 from /usr/include/c++/4.8/iostream:39,
                 from Matrix.cpp:5:
/usr/include/c++/4.8/bits/ios_base.h:924:3: error: in passing argument 1 of ‘std::ios_base& std::right(std::ios_base&)’
   right(ios_base& __base)
   ^

此错误报告对我来说有点不清楚,所以,如果您有任何想法或建议,请不要犹豫与我分享。 我觉得问题来自继承和基类。但如果没有它,我必须复制并粘贴大量代码。

感谢任何建设性的回答!

0 个答案:

没有答案