Search code examples
c++boostc++17stdany

Why is there no unsafe_any_cast for std::any?


My local version of the Boost headers (1.56.0) has the following functions defined in boost/any.hpp, copied verbatim:

// Note: The "unsafe" versions of any_cast are not part of the
// public interface and may be removed at any time. They are
// required where we know what type is stored in the any and can't
// use typeid() comparison, e.g., when our types may travel across
// different shared libraries.
template<typename ValueType>
inline ValueType * unsafe_any_cast(any * operand) BOOST_NOEXCEPT
{
    return &static_cast<any::holder<ValueType> *>(operand->content)->held;
}

template<typename ValueType>
inline const ValueType * unsafe_any_cast(const any * operand) BOOST_NOEXCEPT
{
    return unsafe_any_cast<ValueType>(const_cast<any *>(operand));
}

Even though the online documentation does not even acknowledge their existence: http://www.boost.org/doc/libs/1_59_0/doc/html/any/reference.html

I noticed that std::any also does not seem to have support for an unsafe any cast.

Why does the C++17 standard not introduce std::unsafe_any_cast?

If an exact reason cannot be found (or if it was simply never proposed), what would be the most compelling arguments to not provide unsafe access to the value stored in an std::any object?


Solution

  • std::any is a type-safe container for single values of any type.

    Note from the comment in the snippet you posted, that Boost's unsafe_any_cast is not part of the public interface. It is an implementation detail, and is not meant to be used by the end-user. That is why it is not mentioned in the documentation.

    Promoting it to the public interface would break the purpose of having a type-safe container in the first place.