-4

我使用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&?我尝试将变量设置为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's... 它是什么?我该如何解决这个“铸造”操作?

4

1 回答 1

3

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

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

从您的代码片段中,您可能需要;

boost::any_cast<ValueType>(operand.value())
于 2016-06-17T09:44:04.863 回答