boost :: optional的隐式强制转换为bool会消失吗?

时间:2015-05-21 00:15:30

标签: c++ boost optional

我开始将vc ++ 10 / boost 1.48代码库移植到vc ++ 12 / boost 1.57,我收到一个错误,即boost :: optional无法转换为bool。我认为这是boost :: optional的一个特性,它被删除了吗?

示例:

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

给出

Error   21  error C2440: 'return' : cannot convert from 'boost::optional<int32_t>' to 'bool'

1 个答案:

答案 0 :(得分:10)

是。 Boost 1.55仍使用Safe Bool Idiom

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

Boost 1.56Boost 1.57Boost 1.58现在使用此宏:

BOOST_EXPLICIT_OPERATOR_BOOL_NOEXCEPT()

大致是:

#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

我猜你没有定义BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS - 而且由于你的编译器支持显式转换运算符,你应该保持这种方式!