3

我的本地版本的 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));
}

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

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

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

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

4

1 回答 1

5

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

请注意,从您发布的片段中的评论中可以看出,Boostunsafe_any_cast不是公共界面一部分。它是一个实现细节,并不打算由最终用户使用。这就是为什么文档中没有提到它的原因。

将它提升到公共接口会破坏首先拥有类型安全容器的目的。

于 2018-01-17T14:01:43.673 回答