为什么出于std :: is_convertible的目的boost :: optional <t>无法转换为bool

时间:2018-11-15 12:11:51

标签: c++ boost-optional

我有

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; 
    }
}

我在这里想念什么?

1 个答案:

答案 0 :(得分:10)

boost::optional的{​​{1}}是operator bool。它可以在explicit的条件内工作,因为它是contextual conversion

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

以下编译

if

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

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