2017-05-28 47 views
0

我想在模板類上聲明一個模板方法,它不適合我。 這是更好地使這裏給出的代碼解釋是: 我有這個類:聲明一個模板類的模板方法

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 
} 

我想這個代碼,以任何2種類型的矩陣工作和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; 

然而,當,我試圖編譯上面的代碼,我得到這個錯誤:

no match for âoperator+ in m1+m2

+2

你希望'operator +'能夠只添加相同size_的矩陣,但是通過使用'Matrix '作爲它的參數與自己矛盾,其中'c'和'd'可能不等於'a '和'b'分別。 – ForceBru

+2

除此之外,您還目前有錯誤,你應該知道https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file –

+0

@ForceBru我不是與自己相矛盾,但我希望錯誤在運行時顯示,而不是在編譯時顯示。我想要編譯代碼,然後給我錯誤。 – Loay

回答

2

將您的代碼更改爲此(n OT考慮,我認爲可能是錯在這裏的事情,不僅改變了它,使其編譯)

#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. operator+不能在被定義3210文件在評論中提到,它必須放在頭文件中(如果你想分割接口和實現,你可以做的最好的是In the C++ Boost libraries, why is there a ".ipp" extension on some header files
  4. 我通常喜歡首先有public部分,因爲它給出了讀者可以更好地瞭解該課程的界面。
+0

當T和T2是不同類型時,你會做什麼? –

+0

@ n.m。你的意思是在'operator +'成員中?你能澄清嗎? – Curious

+0

是的,e,g,當你添加'Matrix '和'Matrix '會發生什麼?返回'* this'會編譯,但實際添加又如何? –