声明模板类的模板方法

时间:2017-05-28 14:38:13

标签: c++ templates matrix

我正在尝试在模板类上声明一个模板方法,但它对我不起作用。 最好通过给出代码来解释这里是: 我有这门课:

  

matrix.h

template <class T,int a,int b>
class Matrix {
private:
   int x;
   int y;
public:
   class IllegalOperation();
   template<T,int c,int d>
   Matrix<T,a,b> operator+(const Matrix<T,c,d> m);
   //...
}
  

matrix.cpp

template<class T,int a,int b>
template<T,int c,int d>
Matrix<T,a,b> Matrix<T,a,b>::operator+(const Matrix<T,c,d> m){
  if(a!=c || b!=d) throw IllegalOperation();
  // add matrices and return the result
}

我希望此代码适用于任何两种类型的Matrix和Matrix,其中a,b,c和d可以不同。 例如,我希望此代码编译并返回错误(在运行时):

const Matrix<int, 3, 2> m1;
const Matrix<int, 7, 3> m2;
// init m1 and m2
m1+m2;

虽然此代码应编译并成功运行:

const Matrix<int, 3, 2> m1;
const Matrix<int, 3, 2> m2;
// init m1 and m2
m1+m2;

但是,当我尝试编译上面的代码时,我收到此错误:

  

与m1 + m2

中的âoperator+不匹配

1 个答案:

答案 0 :(得分:2)

将您的代码更改为此(不考虑我认为可能在这里出错的内容,只更改它以使其编译)

#include <type_traits>

template <typename T,int a,int b>
class Matrix {
public:
    template<typename T2, int c, int d>
    Matrix<T,a,b> operator+(const Matrix<T2, c, d>& m) const;
private:
    int x;
    int y;
};

template <typename T,int a,int b>
template <typename T2, int c, int d>
Matrix<T, a, b> Matrix<T, a, b>::operator+(const Matrix<T2, c, d>&) const {
    if(a != c || b != d) {
        throw IllegalOperation{};
    }
    /*constexpr*/ if (!std::is_same<T, T2>::value) {
        throw Error{};
    }
    return *this;
}

int main() {
    const Matrix<int, 3, 2> m1{};
    const Matrix<int, 7, 3> m2{};
    m1 + m2;
    return 0;
}

我在这里做了一些改变

  1. operator+const,你试图在const对象上调用非const成员函数,不起作用
  2. 加法运算符中的矩阵参数现在通过引用
  3. 获取
  4. operator+无法在评论中提到的.cpp文件中定义public,它必须放在头文件中(如果你想拆分界面和实现,你可以做的最好是In the C++ Boost libraries, why is there a ".ipp" extension on some header files
  5. 我通常喜欢首先使用 "**/*.js": { "when": "$(basename).ts" }, "**/**.js": { "when": "$(basename).tsx" } 部分,因为它让读者更好地了解了课程的界面。