4

我有

auto result = std::is_convertible
    < boost::optional<int>
    , bool
    >::value;

static_assert( result , "task should return bool" );

它无法编译。std::is_convertible的定义是

template< class From, class To > struct is_convertible;

并且 optional 显然可以转换为布尔值,因为我们总是像这样使用它

void(boost::optional<int> const & value){
    if(value){
        std::cerr << *value << endl; 
    }
}

我在这里想念什么?

4

1 回答 1

10

boost::optionaloperator boolexplicit。_ 它在if' 条件下工作,因为它是上下文转换

您需要std::is_constructible,它会尝试执行显式转换。

以下编译

static_assert
    ( std::is_constructible<bool, boost::optional<int>>::value
    , "msg" );

并且以下内容无法编译,因为 optional 不能转换为 int

static_assert
    ( std::is_constructible<int, boost::optional<int>>::value
    , "msg" );
于 2018-11-15T12:19:19.873 回答