重载运算符&&和||短路在 C++17 中

Short circuit of overloaded operator && and || in C++17

我读到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.

(我的重点)。

找不到支持短路的 C++17 的任何资源或代码示例 对于运算符&& 和运算符||。 它与C++17参数包折叠表达式有关吗?尝试使用它但无法为重载运算符 && 和 || 创建短路行为使用 C++17 折叠表达式。

代码:

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;
}

输出:

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

注意:从左到右的顺序在使用 C++17 标志编译的当前 gcc 版本中也没有发生。

该声明与短路评估无关。这是关于评估操作数的顺序。

C++17 之前,计算重载的 && 和 || 操作数的顺序是编译器定义的。 C++17 为 && 和 || 定义了从左到右的显式求值顺序,无论它们是否重载。

短路评估仍然只适用于内置运算符。

请注意,在您引用的实际页面上,突出显示的部分是适用于特定版本的部分。那部分是关于顺序的,不是关于短路评估的部分。