我使用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... 它是什么?我该如何解决这个“铸造”操作?