Conversion of boost::optional to bool

dimba picture dimba · Feb 7, 2011 · Viewed 13.9k times · Source

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?

Answer

Daniel Gehriger picture Daniel Gehriger · Feb 7, 2011

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.