2016-06-26 11 views
3

実験的にenumクラスの演算子のオーバーロードを試行しているときに問題が発生しましたが、驚くことに単項演算子、つまり++の場合にのみ機能します。曖昧さのためのコンパイラの苦情は:enumクラスのリレーショナル演算子オーバーロード

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を取ることはないでしょうか?

+1

私も試してみました演算子<(const Fruit&l、const Fruit&r)が同じ結果を得ました。 – user6514323

+0

私はあなたの心配を得ることはありません。あなたの[オペレータは実際に呼ばれています](http://coliru.stacked-crooked.com/a/c3f8b15987049420)? –

+0

私のために働く。 http://ideone.com/GO6HWR。 –

答えて

4

これは、2010年以降に開かれたVisual C++コンパイラのバグであり、マイクロソフトは明らかにすぐに修正されないようです。

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++.


良い回避策はまさに、あなたが達成しようとしているかに依存します。

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

std::set<Fruit> s; 

をそれとも、この目的のためにファンクタクラスを定義します:あなたはstd::mapstd::setのような標準的なコンテナクラスにあなたのFruitを入れたい場合たとえば、あなたはstd::lessを専門に検討する必要があります

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

std::set<Fruit, FruitComparison> s; 

あなたがアルゴリズムの比較が必要な場合は、その後、あなたは、ラムダを使用することがあります:

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