2011-10-11 25 views
4

如果我考慮<複雜>從2008年MSVC頭,我發現,每個運營商定義數加倍_其他類型的模板操作中,像例如雙(?)定義

_Myt& operator+=(const _Myt& _Right) 
{ // add other complex 
    this->_Add(_Right); 
    return (*this); 
} 
template<class _Other> inline 
_Myt& operator+=(const complex<_Other>& _Right) 
{ // add other complex 
    this->_Add(_Right); 
    return (*this); 
} 

問題這就是爲什麼單獨的第二個定義不夠?

PS: 看來在gcc中只有第二個定義存在,現在我不再擔心了。 :)

+3

從我的頭頂開始:函數重載發生在模板解析之前。根據一般訪問'T :: operator + =(const T&)'的代碼無法找到它,我猜 – sehe

+0

@sehe:將其作爲答案並接收+1 :) – Constantinius

+0

@sehe:我不確定代碼如何合法地這樣做。你有一個例子嗎? – MSalters

回答

3

第一種情況也可以捕獲右邊的可兌換_Myt

class MyComplex { 
    // ... 
    public: 
    operator std::complex<double>() const; 
    operator std::complex<float>() const; 
}; 
std::complex<double> i; 
i += MyComplex(1,1); // Unambiguously uses the first form. 
+0

+1更理智的邏輯:) – sehe