【发布时间】: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& ?我尝试将变量设置为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<unsigned>(function_returning_optional_boost_any());