Safe bool for class Result


Just throwing this out there Jules:

But only because I know how much you love over-engineering.


I do love a bit of over-engineering, and that’s a good article! I think their full-blown solution would be a bit much for my little Result class, but thanks for reminding me that I need to give it a private operator int() to avoid it being accidentally cast to a number or pointer.

(In fact, since the purpose of Result is to replace a bunch of functions that currently return a bool, then even in its current state it won’t cause any errors that aren’t already there. And if I prevent it being accidentally cast to an int or void*, then it’ll already be an improvement on functions that just return a bool directly).


It’s funny you speak about safebool, as I’ve read the same article in the last weeks.
I’ve implemented something similar, and then realized that it was overkill and presents a lot of “collateral damage” and finally set up my own solution.
[1]: If you have an operator int() in your class (like mine does), then the operator int() takes precedence over the operator “pointer to member”, so you’re f*cked. (Same goes for operator const char (), void() etc…)
[2]: The design of a safe bool is not obvious to understand, since it’s a workaround to a C++ limitation. This means that people reading the code will not actually understand the concept and might implement it wrongly.
[3]: If you can wait until all compiler are C++x0 valid, you’ll get “explicit” conversion operator that solve this exact issue.

So finally, I’ve written an operator bool() + operator != + operator == in my class, and then added all the other operator as private “template bool operator !=(const T & t) const;” to avoid any other unfortunate conversion.