Conversions to bool are generally a good thing: they're like a uniform interface for checking the "validity" of an object, if the "validity" is unambiguous - like for pointers. However, as could be see with the invention of the "safe-bool idiom", *implicit* conversions to bool can cause many problems and aren't very favorable. C++11 added explicit conversion operators and so-called *contextual conversions to bool*, which is a definite improvement - but the built-in types still suffer from implicit conversions.
On a slight tangent: Something that has formed in the back of my head in the last few days was an unary postfix `operator?`, which explicitly asks for a contextual conversion to bool. It's basically the conditional operator without the branches.
The idea originally came up when somebody wanted to provide a function which checks the validity of his object by inspecting the underlying `std::optional`-like object which provides an `explicit operator bool`, but not an `engaged()` or `initialized()` or similar function.
That could be seen as an interface-fail, but one has to live with it.
class foo{
std::optional<T> _impl;
// ...
bool test() const{ return _impl; }
};
This obviously won't compile, as the conversion to bool would be considered *implicit* here. We then discussed several "workarounds":
return bool(_impl); // very subjective feeling: meeeeeeeh
return static_cast<bool>(_impl); // unwieldy
return _impl ? true : false; // feels redundant
return _impl && true; // feels redundant and obscure
return !!_impl; // double-banging in C++? oh come on
In comes `operator?`
return _impl?; // concise and (imo) clear
So, returning from that tangent, said `operator?` would then also be used with the fundamental types, providing a clear migration path for code that relies on the implicit conversion to bool.
There's no proposal at this point, as I just want to collect general interest and feedback.
Regards