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

标签 c++ operator-overloading 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

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

最佳答案

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

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

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

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

关于c++ - 重载运算符 && 和 || 短路在 C++17 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41227353/

相关文章:

c++ - 将随机数放入缓冲区以写入文件的有效方法是什么?

c++ - 运算符重载,所有运算符的定义/ header

c++ - Clang 模块与 std <iterator> 和 <boost/move/iterator.hpp> 交互

c++ - 带有 c++17 的 `filesystem` 在我的 mac os x high sierra 上不起作用

c++ - 我们在 C++17 中有自动数组吗?

c++ - 为什么 std::atomic_fetch 将指针作为其输入参数

c++ - 带指针的菱形继承(钻石问题)虚拟成员类型转换

c++ - 错误 : 'xxx' is not a type

c++ - 运算符重载枚举类

c++ - Operator() 作为 Matrix 类的下标