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.
(until c++17)
mark applies to “do not sequence their left operand before the right one, and”. In C++17, a call to overloaded operator function is sequenced in the same way as the corresponding built-in operator. AFAIK you still can't create short circuit behavior. – Snareoperator&&()
can take exactly one argument, so writing it as a variadic template is somewhat misleading. – Ridglee