为什么std :: any没有unsafe_any_cast?

Maa*_*lis 3 c++ boost c++17 stdany

我的Boost标头的本地版本(1.56.0)定义了以下函数boost/any.hpp,逐字复制:

// 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));
}
Run Code Online (Sandbox Code Playgroud)

即使在线文档甚至不承认它们的存在:http://www.boost.org/doc/libs/1_59_0/doc/html/any/reference.html

我注意到,std::any似乎也不支持任何不安全的演员.

为什么不引入C++ 17标准std::unsafe_any_cast

如果找不到确切的原因(或者根本就没有提出),那么最不能提供对存储在std::any对象中的值的不安全访问的最有说服力的论点是什么?

Cás*_*nan 5

std::any是任何类型的单个值的类型安全容器.

从您发布的片断评论请注意,Boost的unsafe_any_cast不是公共接口的一部分.它是一个实现细节,并不意味着最终用户使用.这就是文档中没有提到的原因.

将其推广到公共界面将首先打破拥有类型安全容器的目的.

  • 我不同意最后一句话,std::any 确实有用例,例如调用包含的对象构造函数或类型安全复制。提供不安全的演员表不会破坏这些优势。(缺少 unsafe_cast 是我仍然坚持使用 boost::any 的一个原因) (2认同)