4

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?

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Maarten Bamelis
  • 2,243
  • 19
  • 32

1 Answers1

5

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.

Not a real meerkat
  • 5,604
  • 1
  • 24
  • 55
  • 4
    I do not agree to the last statement, std::any does have use-cases such as calling the contained objects constructor or type-safe copying. Providing an unsafe cast would not break these advantages. (The lack of unsafe_cast is a reason I still stick to boost::any) – Viktor Sehr Jul 06 '18 at 17:58
  • @ViktorSehr Thanks for your comment. Please note that the last paragraph is not the main point in the answer. The main point is that the function `unsafe_any_cast` is not part of the public interface of Boost, which means it may not be available on future versions. The last paragraph adds a view from a design perspective: Having a *public* function whose sole purpose is *breaking the class' contract* is not a good design decision. If you need an unsafe cast, `std::any` (Or `boost::any`, for that matter) is probably not the way to go. – Not a real meerkat Jul 08 '18 at 16:56