Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c++ - why doesn't std::any_cast support implicit conversion?

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?

For example:

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

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)?

question from:https://stackoverflow.com/questions/49428018/why-doesnt-stdany-cast-support-implicit-conversion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

std::any_cast is specified in terms of typeid. To quote cppreference on this:

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...