c++c++17operator-overloadingshort-circuiting

Do overloaded logical operators && and || short-circuit since C++17?


I read in http://en.cppreference.com/w/cpp/language/operators:

The boolean logic operators, operator && and operator ||

Unlike the built-in versions, the overloads do not sequence their left operand before the right one, and (until C++17) cannot implement short-circuit evaluation.

(My emphasis).

Couldn't find any resource or code example for C++17 supporting short-circuit for operator&& and operator||. Is it related to C++17 parameter pack fold expression? tried to play with it but couldn't create short circuit behavior for overloaded operator && and || with C++17 fold expression.

Code:

class A {
    bool val;
public:
    A(bool b) : val(b) { cout << "A born as " << boolalpha << val << endl;}
    template<typename ...Args>
    bool operator&&(Args&&... args) {
        return (val && ... && args.val);
    }    
};

int main() {
    cout << boolalpha;
    cout << ( A{false} && A{true} ) << endl;
    cout << ( A{true} && A{false} ) << endl;
    cout << ( A{false} && A{false} ) << endl;
}

Output:

A born as true
A born as false
false
A born as false
A born as true
false
A born as false
A born as false
false

http://coliru.stacked-crooked.com/a/f0b5325899c2fe6b

Note: the sequence of left to right is also not happening in current gcc version, compiled with C++17 flag.


Solution

  • That statement is not about short-circuit evaluation. It's about the order of evaluating the operands.

    Pre-C++17, the order for evaluating the operands of overloaded && and || was compiler-defined. C++17 defines an explicit order of evaluation of left-to-right for && and ||, whether they are overloaded or not.

    Short circuit evaluation still only applies to the built-in operators.

    Note that on the actual page you cited, the part that is highlighted is what is applied to a specific version. That part is about the sequencing order, not the part about short-circuit evaluation.