boost::optional 对 bool 的隐式转换是否消失了?

Did boost::optional's implicit cast to bool go away?

我开始将 vc++10/boost 1.48 代码库移植到 vc++12/boost 1.57,但出现 boost::optional 无法转换的错误布尔。我以为这是 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'

是的。 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 现在使用这个宏:

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 - 因为你的编译器支持显式转换运算符,所以你应该保持这种状态!