为什么std :: any_cast不支持隐式转换? [英] why doesn't std::any_cast support implicit conversion?
问题描述
为什么 std :: any_cast
从实际存储中进行隐式转换时会引发 std :: bad_any_cast
异常
Why does std::any_cast
throw a std::bad_any_cast
exception when an implicit conversion from the actual stored type to the requested type would be possible?
例如:
std::any a = 10; // holds an int now
auto b = std::any_cast<long>(a); // throws bad_any_cast exception
为什么不允许这样做,是否有解决方法允许隐式转换(如果 std :: any
拥有的确切类型未知)?
Why is this not allowed and is there a workaround to allow an implicit conversion (in case the exact type that std::any
holds is unknown)?
推荐答案
std :: any_cast
是根据 typeid
指定的。在此引用 cppreference :
std::any_cast
is specified in terms of typeid
. To quote cppreference on this:
如果请求的
typeid
抛出std :: bad_any_cast
ValueType
与
不匹配操作数的内容。
Throws
std::bad_any_cast
if thetypeid
of the requestedValueType
does not match that of the contents of operand.
由于 typeid
不不允许实现弄清楚隐式转换是可能的,据我所知, any_cast
也无法知道这是可能的。
Since typeid
doesn't allow the implementation to "figure out" an implicit conversion is possible, there's no way (to my knowledge) that any_cast
can know it's possible either.
否则, std :: any
提供的类型擦除依赖于仅在运行时可用的信息。而且该信息并不像编译器用于确定转换的信息那样丰富。这就是C ++ 17中类型擦除的代价。
To put it otherwise, the type erasure provided by std::any
relies on information available only at run-time. And that information is not quite as rich as the information the compiler has for figuring out conversions. That's the cost of type erasure in C++17.
这篇关于为什么std :: any_cast不支持隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!