Lazy, overloaded C++ && operator?

后端 未结 4 607
情歌与酒
情歌与酒 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: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.

提交回复
热议问题