2016-06-12 49 views
0

我正在學習模板並遇到函數模板。我已經開發出了以下代碼,這些代碼是出於我的創造力或僅僅是好奇心。帶有運算符重載的函數模板

#include<iostream> 
using namespace std; 
template <typename type> 
type Max(type a, type b) 
{ 
    return a > b ? a : b; 
} 
class Foo 
{ 
public: 
    string s1; 
    /* 
    Foo& operator>(Foo &obj) 
    { 
     if (this->s1.length() > obj.s1.length() ? true : false) 
      return *this; 
     return obj; 
    }*/ 
}; 
int main() 
{ 
    cout << Max(2, 3) << endl; 
    cout << Max(2.0, 3.0) << endl; 
    Foo a, b; 
    a.s1 = "AB"; 
    b.s1 = "ABC"; 
    //cout<<Max(a, b).s1; 
} 

我的想法是通過富對象A和B使用最大函數模板和重載「>」操作者並以更大的長度打印對象的字符串。 我在正確的道路上?或者它應該與類模板相關?

+1

'運營商>'正常返回'bool'。 – aschepler

回答

0
#include <iostream> 

using namespace std; 

template <typename type> 
type Max(type a, type b) 
{ 
    return a > b ? a : b; 
} 

class Foo { 
public: 
    string s1; 
    bool operator > (Foo &obj) { 
     return this->s1.length() > obj.s1.length();   
    } 
}; 

int main() 
{ 
    cout << Max(2, 3) << endl; 
    cout << Max(2.0, 3.0) << endl; 
    Foo a, b; 
    a.s1 = "AB"; 
    b.s1 = "ABC"; 
    cout << Max(a, b).s1; 
} 

這可能是你想要什麼:output results

+0

:函數模板如何直接與對象一起工作,而不需要像類型&Max(常量類型&a,常量類型&b)那樣進行更改。爲什麼我們不需要更改它?這裏的內部函數是什麼?請解釋 – Omkar

+1

因爲我們'我們已經重載了>,所以Max()將返回更大的對象。我們不需要在這裏使用參考。 –

+2

@OMKAR通過不使用引用('&'),'Max()'在比較之前複製'type'對象,然後複製結果。它可以工作,但使用引用會更有效率 –

2

operator>返回bool,否則它不能與return a > b ? a : b;一起使用。

bool operator>(const Foo &obj) 
{ 
    return this->s1.length() > obj.s1.length(); 
} 

BTW1:if (this->s1.length() > obj.s1.length() ? true : false)是多餘的。
BTW2:最好將參數類型設置爲const,因爲obj不會,也不需要修改。

2

你是在正確的道路上,除了>運營商應採取const基準參數,它本身是一個const類方法,並返回一個bool

bool operator>(const Foo &obj) const; 

畢竟,你能指望什麼的>的結果是,與別的,例如:

double a, b; 

// ... 

auto whatisthis= a > b; 

你期望whatisthis是一個double?當然不會,這將是一個bool。任何比較運算符的結果,不僅>應該是bool。它並不是必須的,你可以重載運算符並讓它返回任何東西;但這意味着你無法按照你期望的方式使用它。

2

您的問題的答案是「是的,你在正確的軌道上。」

泛型函數的問題是高效地使用它們。你的Max()函數可以工作,但它可以在整個地方複製對象。

template <typename type> 
const type &Max(const type &a, const type &b) 
{ 
    return a > b ? a : b; 
} 

這解決了對象複製的問題 - 但現在它的喜歡的事情int效率較低。