懒惰,重载C ++和放大器;&安培;运营商? [英] Lazy, overloaded C++ && operator?

查看:131
本文介绍了懒惰,重载C ++和放大器;&安培;运营商?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现我自己的布尔类,但不能复制原始语义和放大器;&放;.下面做作code说明了问题:

I'm trying to implement my own boolean class, but cannot replicate native semantics for &&. The following contrived code demonstrates the issue:



    #include <iostream>>

    class MyBool {
    public:
        bool theValue;
        MyBool() {}
        MyBool(bool aBool) {theValue = aBool;}
        MyBool operator&& (MyBool aBool) {return theValue && aBool.theValue;}
    };

    bool f1() {std::cout << "   First\n"; return false;}
    bool f2() {std::cout << "   Second\n"; return false;}

    int main(int argc, char** argv) {
        std::cout << "Native &&\n";
        f1() && f2();
        std::cout << "Overloaded &&\n";
        MyBool(f1()) && MyBool(f2());
        return 0;
}

当编译和运行,其结果是:

When compiled and run, the result is:



    Native &&
       First
    Overloaded &&
       Second
       First

在换言之,&放大器;&放大器;在布尔变量是懒惰的(因为任何C ++程序员所期望的),但超载和放大器;&安培;是不是(因为这样的C ++程序员,至少没有想到)。

In other words, && on bools is lazy (as any C++ programmer would expect) but the overloaded && isn't (as this C++ programmer at least didn't expect).

有没有一种方法,使超载和放大器;&安培;懒?我能找到的各种全懒惰评估计划,提供哈斯克尔一样的功能,但他们似乎对我的用例完整的矫枉过正。

Is there a way to make overloaded && lazy? I can find various full-on lazy evaluation schemes to provide Haskell-like functionality, but they seem like complete overkill for my use case.

推荐答案

您应该不超载布尔运算符和放大器;&安培; ,因为你失去了短路的评价,因为你发现。

You should not overload bool operator&&, since you lose short circuit evaluation, as you have discovered.

正确的做法是给你的类一个bool转换操作符

The correct approach would be to give your class a bool conversion operator

class MyBool {
 public:
  bool theValue;
  MyBool() {}
  MyBool(bool aBool) : theValue(aBool) {}
  explicit operator bool() { return theValue; }
};

需要注意的是显式转换运营商需要C ++ 11合规性。如果你没有这个,看看在安全布尔成语

这篇关于懒惰,重载C ++和放大器;&安培;运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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