Can (a==1)&&(a==2)&&(a==3) evaluate to true? (and can it be useful?)

前端 未结 8 1348
北荒
北荒 2021-01-15 11:34

Inspired by another question regarding java-script language. Can the expression

 (a==1)&&(a==2)&&(a==3)

evaluate to true i

相关标签:
8条回答
  • 2021-01-15 12:19

    Could be somewhat useful.

    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    
    struct Foo {
        std::vector<int> v = {1,2,3};
    };
    
    bool operator==(const Foo& foo, int i) {
        return std::any_of(foo.v.begin(), foo.v.end(), [=](int v){ return v == i; });
    }
    
    int main() {
        Foo a;
    
        if (a==1 && a==2 && a==3)
            cout << "Really??" << endl;
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-15 12:23

    Operator overloading and macros are trivial solutions to such a riddle.

    And if so, can it actually be useful?

    Well, with some imagination... One possible use case I can think of are unit tests or integration tests in which you want to make sure that your overloaded operator== for some class works correctly and you know for sure that it works incorrectly if it reports equality for different operands when it's not supposed to do that:

    class A {
    public:
        A(int i);
        bool operator==(int i) const;
        // ...
    };
    
    A a(1);
    
    if ((a==1)&&(a==2)&&(a==3)) {
        // failed test
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题