[英]C++ how to use std::function with overloaded operators of different return types
[英]Support different types on overloaded operators?
我懷疑,支持不同類型的自定義類的運算符正確嗎? 假設我們有這個:
template<class T>
class C { /* Class implemantation */ }
int main () {
C<int> someObject;
C<double> otherObject;
std::cout << someObject + otherObject;
}
為int類型的C對象和double類型的C對象支持operator +是正確的。
其邏輯上的正確與否取決於您作為類設計者的希望如何使用您的類。 添加someObject
和otherObject
是否合乎邏輯? 添加2
和3.5
是有意義的,但這並沒有說明這是否適合您的代碼。 作為反例,您不能添加basic_string<char>
和basic_string<wchar>
-這種添加沒有意義,因為您必須存儲相同類型的字符-但您可以添加兩個basic_string<T>
,用於任何T
您當然可以使用??
編寫代碼來做到這一點。 待定。
template <typename T>
class C {
..
template <typename U>
C<??> operator+(const C<U>& rhs) {
// ..
}
};
如果希望特定的運算符對某些類型的類進行特殊化處理,則可以隨時編寫特殊的運算符重載,例如:
template<class T>
class C { /* implementation */ };
C<double> operator+ (C<int> a, C<double> b)
{
C<double> ret;
// Do something to ret given a and b
return ret;
}
// Lets make it commutative (is that the right word?)
C<double> operator+ (C<double> a, C<int> b)
{
return b + a;
}
int main(int argc, char** argv)
{
C<int> a;
C<double> b;
C<double> ret1 = a + b;
C<double> ret2 = b + a;
return 0;
}
這僅取決於您想要實現的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.