Conversion function for error checking considered good?

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 e can be implicitly
converted
to a type T if and only if
the declaration T t=e; is well-formed,
for some invented temporary variable t
(§8.5). Certain language constructs
require that an expression be
converted to a Boolean value. An
expression e appearing in such a
context is said to be contextually converted to bool and is well-formed
if and only if the declaration bool t(e); is well-formed, for some
invented temporary variable t (§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:

  • the conditions of if, while, and for statements;
  • the operators of logical negation !, logical conjunction &&, and logical disjunction ||;
  • the conditional operator ?:;
  • the condition of static_assert;
  • the optional constant expression of the noexcept exception specifier;

Leave a Comment