【发布时间】:2017-05-28 14:38:12
【问题描述】:
我正在尝试在模板类上声明一个模板方法,但它对我不起作用。 最好通过给出代码来解释,所以这里是: 我有这门课:
矩阵.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);
//...
}
矩阵.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
}
我希望此代码适用于任何 2 种类型的 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+
【问题讨论】:
-
您希望
operator+能够仅添加相同大小的矩阵,但使用Matrix<T, c, d>作为其参数会自相矛盾,其中c和@ 987654329@ 可能不分别等于a和b。 -
除了你目前遇到的那个错误,你应该知道stackoverflow.com/questions/495021/…
-
@ForceBru 我并没有自相矛盾,但我希望在运行时而不是在编译时显示错误。我希望代码编译然后给我错误。
-
“我希望在运行时而不是在编译时显示错误”然后不要将矩阵大小作为模板参数。
-
@Loay " 我认为在我的情况下是分离实现。" 好吧,那根本行不通:-P