Search code examples
c++boostoption-type

Why is boost::optional::is_initialized() deprecated?


I noticed today that boost::optional::is_initialized() is marked as deprecated in the Boost 1.64.0 reference. My projects are liberally sprinkled with is_initialized() to check if the boost::optional contains a value.

I don't see any other way to properly test if a boost::optional is initialized, am I missing something?

The boost::optional has a explicit operator bool(), meaning that I can do if(foo){...} if foo is a boost::optional. However, this would give wrong results if foo is a boost::optional<bool> or some other boost::optional<T> where T is convertible to bool.

What does Boost expect users to do?


Solution

  • However, this would give wrong results if foo is a boost::optional or some other boost::optional where T is convertible to bool.

    No, because there is no implicit conversion to the underlying type. The "truthiness"¹ of an optional always refers to its initialized state.

    The only time you may have gotten the impression that implicit conversions happen is in relational operators. However, that's not doing implicit conversion to the underlying type, instead does lifting of the operators, explicitly.

    ¹ by which I mean contextual (explicit) boolean conversion

    Update

    Indeed for boost::optional<bool> there's the caveat in pre-c++11 mode:

    Second, although optional<> provides a contextual conversion to bool in C++11, this falls back to an implicit conversion on older compilers

    In that case it is clearly better to explicitly compare to boost::none.