代码之家  ›  专栏  ›  技术社区  ›  bradgonesurfing

为什么Boost::Optional<t>Not convertable to bool for the purpose of std::is_convertible

  •  4
  • bradgonesurfing  · 技术社区  · 7 年前

    我有

    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;
    

    可选项显然可以转换为布尔值,因为我们总是使用它

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

    我这里缺什么?

    1 回复  |  直到 7 年前
        1
  •  10
  •   bradgonesurfing    7 年前

    boost::optional operator bool explicit . 它在一个 if 的条件,因为它是 contextual conversion .

    你需要 std::is_constructible ,尝试执行显式转换。

    以下汇编

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

    以下代码无法编译,因为可选代码不能转换为int

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