2016-05-27 8 views
2

MyClassのオブジェクトの連鎖比較を行うオプションを追加したいと思います。たとえば:すべてが等しい場合、それはtrueを返すように連鎖等価演算子オーバーロード

MyClass one; 
MyClass two; 
MyClass three; 
/*....*/ 
if (one == two == three){ 
    /*....*/ 
} 

、そうでなければfalseを返します。 私は現在MyClassの唯一の2つのインスタンスを比較するときに正常に動作します。この演算子オーバーロードがあります。

bool operator==(const MyClass &other); 

私はone==two==threeので、私はそのようなものであることを私のoperator==を変更する必要がありますね((one==two)==three)に等しいことを理解:

MyClass& operator==(const MyClass &other); 

しかし、私は行(連鎖)の2つ以上のインスタンスを比較できるようにこれを完了する方法を理解することができませんでした。 純粋に理論的な問題として

+5

通常のセマンティクスに従わず、 'if(one == two && two == three)'を使うのはなぜですか? – NathanOliver

+6

お願いします** ** –

+1

@ NathanOliver:実際には、「EqualExpr」オブジェクトはすべての等価を評価する必要がありますが、通常のセマンティクスは短絡する可能性があります。 – user2658323

答えて

4

コメントで指摘したように、それは、このような方法で、通常のセマンティクスを破るために良いではありません。上記のように、Principle of least Astonishmentに従ってください。

しかし、行(連鎖)内の2つ以上のインスタンスを比較できるようにするには、これを完了する方法を理解できませんでした。

#include <iostream> 

using namespace std; 

class MyClass { 
public: 
    MyClass(int x_) : x(x_), isfalse(false) {} 

    const MyClass& operator==(const MyClass& rhs) const { 
     if(!isfalse && x == rhs.x) { 
      return rhs; 
     } 
     return FalseInst; 
    } 
    operator bool() const { 
     return !isfalse; 
    } 
private: 
    int x; 
    MyClass() : x(), isfalse(true) {} 
    const bool isfalse; 
    static MyClass FalseInst; 
}; 

MyClass MyClass::FalseInst; 

int main() 
{ 
    MyClass one(1); 
    MyClass two(1); 
    MyClass three(1); 

    if(one == two == three) { 
     cout << "Yay!" << endl; 
    } 

    MyClass four(1); 
    MyClass five(0); 
    MyClass six(0); 

    if(!(four == (five == six))) { 
     cout << "Yay!" << endl; 
    } 
} 

Live Demo


:私はそれがとても行うには本当に良いアイデアだと思いますが、ここではワーキングソリューションだということ

ありません1)コンパイラによって発行された警告に注意してください。

+0

最小のオーバーヘッドで非常に印象的なソリューション。 '==(two == three)'は別の値を持つ 'three 'で区切っていますが、 – coyotte508

+0

@ coyotte508 THXを指摘して固定しました。 –

+0

今、 'one == two == three'は' two'と 'three'が' 0'でそれを打ち破っています – coyotte508

3

、ここでそれを解決する方法である:

#include <iostream> 
using namespace std; 

class A { 
public: 
    int x; 

    A(int x = 0) : x(x) {} 

    struct Cmp { 
     const A *ptr; 
     mutable bool val; 

     operator bool() const { 
      return val; 
     } 

     const Cmp &operator == (const A &other) const { 
      return other == *this; 
     } 
    }; 

    bool isEqualTo (const A &other) const { 
     return x == other.x; 
    } 

    Cmp operator == (const A &other) const {   
     return {this, isEqualTo(other)}; 
    } 

    const Cmp &operator == (const Cmp &other) const { 
     //other.val = other.val && (*this == *other.ptr).val; 
     other.val &= other.ptr->isEqualTo(*this); 
     return other; 
    } 
}; 

int main() { 
    cout << (A(10) == A(10) == A(10)) << endl; 
    cout << (A(10) == A(9) == A(10)) << endl; 

    return 0; 
} 
関連する問題