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

前端 未结 8 1509
北荒
北荒 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:07

    I assume a requirement is a valid program free of undefined behaviour. Otherwise simply introduce something like a data race and wait for the right circumstances to occur.

    In a nutshell: Yes, it is possible for user-defined types. C++ has operator overloading, so the related answers from the JavaScript question apply. a must be a user-defined type because we compare against integers and you cannot implement operator overloads where all parameters are built-in types. Given that, a trivial solution could look like:

    struct A {}
    bool operator==(A, int) { return true; }
    bool operator==(int, A) { return true; }
    

    Can something like this be useful? As the question is stated: almost certainly not. There is a strong semantic meaning implied by the operator symbols used in their usual context. In the case of == that’s equality comparison. Changing that meaning makes for a surprising API, and that’s bad because it encourages incorrect usage.

    However there are libraries that explicitly use operators for completely different purposes.

    • We have an example from the STL itself: iostream’s usage of << and >>.
    • Another one is Boost Spirit. They use operators for writing parsers in an EBNF like syntax.

    Such redefinitions of the operator symbols are fine because they make it perfectly obvious that the usual operator symbols are used for a very different purpose.

提交回复
热议问题