Lazy, overloaded C++ && operator?

后端 未结 4 597
情歌与酒
情歌与酒 2021-01-18 01:07

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



          


        
相关标签:
4条回答
  • 2021-01-18 01:34

    You can make almost anything evaluate lazily with the expression template idiom, including but not limited to the operators whose built-in versions short-circuit. But that's more work than you need for this one case, since then your MyBool class would require a lot more code.

    0 讨论(0)
  • 2021-01-18 01:41

    Is there a way to make overloaded && lazy?

    No.

    0 讨论(0)
  • 2021-01-18 01:51

    If you really want short-circuiting and are willing to sacrifice the operator syntax, you can rename your operator&& method to _and, define an AND() macro, and write AND(x,y) instead of x&&y.

    #define AND(x,y) (x._and(x.theValue ? y : MyBool(false)))
    

    With some macro hacks you can have AND() accept a variable number of parameters.

    The _and() method here is not intended to be used "publicly" here but must be declared public since you can't friend a macro.

    For something as simple as your MyBool class, this is probably unnecessary. But if you need your operator&& to have special side-effects like updating some state on this, then this gets the job done.

    0 讨论(0)
  • 2021-01-18 01:56

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

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

    Note that explicit conversion operators require C++11 compliance. If you do not have this, have a look at the safe bool idiom.

    0 讨论(0)
提交回复
热议问题