Did boost :: optional add an implicit cast to bool?

I started porting vC ++ 10 / boost 1.48 codebase to vC ++ 12 / boost 1.57 and I get an error message that boost :: optional cannot convert to bool. I thought this was a feature of boost :: optional, did it go away?

Example:

bool fizz(){ boost::optional<int32_t> buzz; return buzz; } 

gives

 Error 21 error C2440: 'return' : cannot convert from 'boost::optional<int32_t>' to 'bool' 
+8
c ++ boost optional
source share
1 answer

Yes. Boost 1.55 still used the safe Bool idiom :

 // implicit conversion to "bool" // No-throw operator unspecified_bool_type() const { return this->safe_bool() ; } 

Boost 1.56 , Boost 1.57, and Boost 1.58 now use this macro:

 BOOST_EXPLICIT_OPERATOR_BOOL_NOEXCEPT() 

which is approximately equal to:

 #if !defined(BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS) explicit operator bool() const noexcept; #else if !defined(BOOST_NO_UNSPECIFIED_BOOL) operator boost::detail::unspecified_bool_type () const noexcept; #else operator bool () const noexcept; #endif 

I assume that you do not have BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS defined - and since your compiler supports explicit conversion operators, you should probably save it that way!

+10
source share

All Articles