为什么 std::any 没有 unsafe_any_cast?
Why is there no unsafe_any_cast for std::any?
我的本地版本的 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
对象中的值的不安全访问的最有说服力的论点是什么?
std::any
是一个 类型安全的 容器,用于任何类型的单个值。
请注意您发布的代码段中的评论,Boost 的 unsafe_any_cast
不是 public 界面的一部分。它是一个实现细节,不打算由最终用户使用。这就是文档中未提及的原因。
将其提升到 public 接口首先会破坏拥有类型安全容器的目的。
我的本地版本的 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
对象中的值的不安全访问的最有说服力的论点是什么?
std::any
是一个 类型安全的 容器,用于任何类型的单个值。
请注意您发布的代码段中的评论,Boost 的 unsafe_any_cast
不是 public 界面的一部分。它是一个实现细节,不打算由最终用户使用。这就是文档中未提及的原因。
将其提升到 public 接口首先会破坏拥有类型安全容器的目的。