【问题标题】:boost::any_cast and std::optional'sboost::any_cast 和 std::optional 的
【发布时间】:2016-06-17 09:17:10
【问题描述】:

我使用boost::any,并且有一些函数可以检索这样的值,但可能会失败,所以它实际上返回std::optional<boost::any>(嗯,现在是std::experimental::optional)。现在,没有可选的,我使用boost::any_cast(my_retrieved_any) 取回我输入的值。为了处理可选情况,我编写了以下内容:

template<typename ValueType>
inline const optional<ValueType> boost_any_cast(const optional<boost::any>& operand)
{
    return operand ? boost::any_cast(operand.value()) : nullopt;
}

但这不能编译(使用 Boost 1.58 和 GCC 4.9.3)。我明白了:

/file.cpp(12): error: no instance of overloaded function "boost::any_cast" 
matches the argument list
            argument types are: (const boost::any)

这怎么可能?为什么论点不是 boost::any&amp; ?我尝试将变量设置为operand.value(),然后将其传递给any_cast——但这似乎也无济于事:

template<typename ValueType>
inline const optional<ValueType> boost_any_cast(const optional<boost::any>& operand)
{
    if (operand) {
        boost::any x(operand.value());
        return boost::any_cast(x);
    }
    return nullopt;
}

这让我明白了:

/file.cpp(13): error: no instance of overloaded function "boost::any_cast"
 matches the argument list
            argument types are: (boost::any)

关于boost::any,一定有什么我没有考虑到的……是什么?我该如何解决这个“铸造”操作?

【问题讨论】:

  • @uhohsomebodyneedsapupper:见编辑。
  • list 是什么类型的?你能提供调用boost_any_cast()的代码吗?
  • @JanKorous:代码中没有任何列表,它是函数的“参数列表”。而调用 boost_any cast() 的代码是auto x = boost_any_cast&lt;unsigned&gt;(function_returning_optional_boost_any());

标签: c++ optional boost-any


【解决方案1】:

boost::any_cast 需要一个模板参数;

template<typename T> T any_cast(const any &);

从你的代码sn-p,你可能需要;

boost::any_cast<ValueType>(operand.value())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-28
    • 2021-09-05
    • 2014-11-21
    • 2018-02-12
    • 1970-01-01
    • 2021-05-16
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多