我正在處理兩個定義真實和複雜數據類型的包裝類。每個類定義了重載的構造函數,以及四個算術運算符+, - ,*,/和五個賦值運算符=,+ =等。爲了避免重複代碼,我考慮使用左右模板函數 - 手側操作者的參數是不同的數據類型的:模板運算符模糊過載
// real.h
class Real {
public:
explicit Real(const double& argument) {...}
explicit Real(int argument) {...}
...
friend const operator*(const Real&; const Real&);
template <class T> friend const Real operator*(const Real&, const T&);
template <class T> friend const Real operator*(const T&, cont Real&);
// Here, T is meant to be a template parameter for double and int
// Repeat for all other arithmetic and assignment operators
};
// complex.h
class Complex {
public:
explicit Complex(const Real& realPart) {...}
explicit Complex(const Real& realPart, const Real& imaginaryPart) {...}
// Overload for double and int data types
...
friend const operator*(const Complex&, const Complex&);
template <class T> friend const Complex operator*(const Complex&, const T&);
template <class T> friend const Complex operator*(const T&, cont Complex&);
// Here, T is is a template parameter for Real, double and int
...
};
這裏的問題是,這樣的代碼:
//main.cpp
void main() {
Complex ac(2.0, 3.0);
Real br(2.0);
Complex cc = ac * br;
}
返回編譯器(GCC)錯誤曖昧過載'operator *'in'ac * BR」,因爲編譯器不能告訴之間的區別:
template <class T> friend const Complex operator*(const Complex&, const T&)
[與T =真]template <class T> friend const Real operator*(const T&, cont Real&)
[與T =復]
是否有辦法在模板運算符*中定義類Real時指定T不能成爲Complex?或者我必須不使用模板,併爲每個可能的參數數據類型組合定義每個運算符?或者有沒有辦法重新設計代碼?
確實應該使構造函數明確(編輯問題)。但是,在這種情況下,使它們顯式不會消除編譯錯誤。 – ASV 2009-10-27 13:54:39