c++ - 为什么 std::any_cast 不支持隐式转换?

标签 c++ c++17

当可以从实际存储的类型隐式转换到请求的类型时,为什么 std::any_cast 会抛出 std::bad_any_cast 异常?

例如:

std::any a = 10;  // holds an int now
auto b = std::any_cast<long>(a);   // throws bad_any_cast exception

为什么不允许这样做,是否有允许隐式转换的解决方法(以防 std::any 持有的确切类型未知)?

最佳答案

std::any_cast 是根据 typeid 指定的。报价 cppreference对此:

Throws std::bad_any_cast if the typeid of the requested ValueType does not match that of the contents of operand.

自从 typeid不允许实现“找出”隐式转换是可能的,(据我所知)any_cast 也不可能知道它是可能的。

换句话说,std::any 提供的类型删除依赖于仅在运行时可用的信息。而且这些信息并不像编译器用于计算转换的信息那么丰富。这就是 C++17 中类型删除的代价。

关于c++ - 为什么 std::any_cast 不支持隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49428018/

相关文章:

c++ - 添加派生类导致ghost错误

c++ - 编译时检查是否有两个具有相同模板参数的模板实例化

c++ - 将 std::filesystem::path 传递给函数段错误

c++ - std::string_view 文字是否保证以 null 结尾?

c++ - 为什么需要指针来初始化堆上的对象,而不是堆栈上的对象?

c++ - 如何将指向 char 的指针转换为指向 int 的指针

c# - 需要帮助理解 _set_security_error_handler()

c++ - 检测类是否具有带签名的构造函数

c++ - 在函数调用时从异构初始化列表构建元组

c++ - 停止接受新连接