Search code examples
c++boost-optional

Why is boost::optional<T> not convertable to bool for the purposes of std::is_convertible


I have

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

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

and it fails to compile. The definition of std::is_convertible is

template< class From, class To > struct is_convertible;

and optional is clearly convertible to boolean because we always use it like

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

what am I missing here?


Solution

  • boost::optional's operator bool is explicit. It works inside an if's condition, because it is a contextual conversion.

    You need std::is_constructible, which tries to perform an explicit conversion.

    The following compiles

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

    and the following fails to compile because optional is not convertible to int

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