I'd like to have a simple way of checking for an object to be valid. I thought of a simple conversion function, something like this:
operator bool() const { return is_valid; } Checking for it to be valid would be very simple now
// is my object invalid? if (!my_object) std::cerr << "my_object isn't valid" << std::endl; Is this considered a good practise?
In C++03, you need to use the safe bool idiom to avoid evil things:
int x = my_object; // this works In C++11 you can use an explicit conversion:
explicit operator bool() const { // verify if valid return is_valid; } This way you need to be explicit about the conversion to bool, so you can no longer do crazy things by accident (in C++ you can always do crazy things on purpose):
int x = my_object; // does not compile because there's no explicit conversion bool y = bool(my_object); // an explicit conversion does the trick This still works as normal in places like if and while that require a boolean expression, because the condition of those statements is contextually converted to bool:
// this uses the explicit conversion "implicitly" if (my_object) { ... } This is documented in §4[conv]:
An expression
ecan be implicitly converted to a typeTif and only if the declarationT t=e;is well-formed, for some invented temporary variablet(§8.5). Certain language constructs require that an expression be converted to a Boolean value. An expressioneappearing in such a context is said to be contextually converted tobooland is well-formed if and only if the declarationbool t(e);is well-formed, for some invented temporary variablet(§8.5). The effect of either implicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.
(What makes the difference is the use of bool t(e); instead of bool t = e;.)
The places were this contextual conversion to bool happens are:
if, while, and for statements;!, logical conjunction &&, and logical disjunction ||;?:;static_assert;noexcept exception specifier;No, a simple bool conversion operator is not, as you can now make evil comparisions between unrelated types. Generally, yes, a conversion function is a-okay. Just use the right one (safe-bool idiom). I can't explain it any better than the given links.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With