c++option-typeboost-any

boost::any_cast and std::optional's


I use boost::any, and have some function which retrieves such a value, but may fail, so it actually returns std::optional<boost::any> (well, for now it's std::experimental::optional). Now, without the optional, I get my typed value back using boost::any_cast(my_retrieved_any). To handle the optional case, I've written the following:

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

But this doesn't compile (with Boost 1.58 and GCC 4.9.3). I get:

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

How is this possible? Why is the argument not boost::any& ? I tried setting a variable to operand.value(), then passing that to the any_cast - but that didn't seem to help either:

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;
}

This gets me:

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

There must be something I'm not taking into account regarding boost::any's... what is it? And how can I fix this "casting" operation?


Solution

  • The boost::any_cast requires a template argument;

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

    From you code snippet, you probably need;

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