dimba dimba - 1 year ago 128
C++ Question

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
'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 Source

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

void func(boost::optional<int> optionalArg)
    if (optionalArg) {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download