Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 542
dimba Avatar asked Feb 07 '11 15:02

dimba


1 Answers

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.

like image 189
Daniel Gehriger Avatar answered Sep 27 '22 19:09

Daniel Gehriger