当可以从实际存储的类型隐式转换到请求的类型时,为什么 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 thetypeid
of the requestedValueType
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/