I\'m trying to implement my own boolean class, but cannot replicate native semantics for &&. The following contrived code demonstrates the issue:
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.
Is there a way to make overloaded && lazy?
No.
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.
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.