过载操作员短路和||在C ++ 17中 [英] Short circuit of overloaded operator && and || in C++17

查看:60
本文介绍了过载操作员短路和||在C ++ 17中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了 http://en.cppreference.com/w/cpp/language /operators :

布尔逻辑运算符,运算符&&和运算符||

与 内置版本,重载不会对其左操作数进行排序 之前,(直到C ++ 17)无法实现短路 评价.

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折叠表达式.

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.

代码:

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标志编译的情况下,也没有发生从左到右的顺序.

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

推荐答案

该陈述与短路评估无关.这与评估操作数的顺序有关.

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

Pre-C ++ 17,用于评估重载&&操作数的顺序.和||由编译器定义. C ++ 17为&&定义了从左到右的评估的显式顺序.和||,无论它们是否过载.

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.

这篇关于过载操作员短路和||在C ++ 17中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆