Search code examples
c++boosttype-conversionboost-optional

Conversion of boost::optional to bool


How I can prevent the last line of this code from compiling?

#include <boost/optional.hpp>

int main()
{
    typedef boost::optional<int> int_opt;
    int_opt opt = 0;
    bool x = opt;  // <- I do not want this to compile
}

The last line doesn't examine opt's contained int value, but instead compiles as a type conversion to bool, and doesn't seem to be what the user intended.

The safe bool idiom seems to be relevant here?


Solution

  • The whole point of boost::optional is to enable code like this:

    void func(boost::optional<int> optionalArg)
    {
        if (optionalArg) {
           doSomething(*optionalArg);
        }
    }
    

    So the implicit conversion to bool is a feature, and should not be prevented from compiling.