2016-06-26 35 views
3

爲了實驗性目的,當嘗試爲枚舉類重載一個小於運算符時出現問題,但出乎意料地它僅適用於一元運算符,即++。編譯器投訴歧義:枚舉類的關係運算符重載

enum class Fruit 
{ 
    apple, 
    banana, 
    orange, 
    pineapple, 
    lemon, 
}; 

bool operator<(Fruit l, Fruit r) 
{ 
    return true; 
} 

int main() 
{ 
    Fruit f = Fruit::banana; 
    Fruit a = Fruit::apple; 
    std::cout << (a < f); 
} 

編譯器發現明顯比在全球範圍內運營商另一個較少,但爲什麼它不會採取重載一個爲它的精確匹配?

+1

我也試過運算符<(const Fruit&l,const Fruit&r)但得到相同的結果。 – user6514323

+0

我沒有得到你的關注。您的[運營商實際上稱爲](http://coliru.stacked-crooked.com/a/c3f8b15987049420)? –

+0

適合我。 http://ideone.com/GO6HWR。 –

回答

4

這是一個Visual C++編譯器bug,自2010年以來一直開放,微軟顯然不會很快修復。

Visual Studio bug 529700

I can confirm that this is a bug with Visual C++. Unfortunately it does not meet the triage bar for the current release of Visual C++ - but we will keep the issue in our database and we will look at it again during the development phase of a future release of Visual C++.


一個很好的解決方法取決於你正在努力實現的,究竟是什麼。例如,如果你想要把你的Fruit爲標準的容器類像std::mapstd::set,你可能要考慮專業std::less

namespace std 
{ 
    template<> 
    struct less<Fruit> 
    { 
     bool operator()(Fruit const& lhs, Fruit const& rhs) const 
     { 
      // your comparison logic 
     } 
    }; 
} 

std::set<Fruit> s; 

或者你定義一個函數子類用於此目的:

struct FruitComparison 
{ 
    bool operator()(Fruit const& lhs, Fruit const& rhs) const 
    { 
     // your comparison logic 
    } 
}; 

std::set<Fruit, FruitComparison> s; 

如果您需要的算法進行比較,那麼你可能想使用lambda:

std::vector<Fruit> v; 
std::sort(begin(v), end(v), [](Fruit const& lhs, Fruit const& rhs) 
{ 
    // your comparison logic 
});