Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::any_cast without needing the type of the original object

Is it possible to use std::any_cast without putting in the first template argument (the type of the object the any is covering)? I tried using any_cast<decltype(typeid(toCast).name())> but it didn't work.

Also tried to store the objects types from the beginning, but that also didn't work because variables can't store types.

like image 392
Bfyuvf Avatar asked Dec 17 '25 15:12

Bfyuvf


1 Answers

One of the fundamentals principles of C++ is that the types of all objects are known at compile time. This is an absolute rule, and there are no exceptions.

The type of the object in question is std::any. It is convertible to some other type only if that type is also known at compile time.

You will note that std::type_info::name() is not a constexpr expression. The returned string is known only at run time. You are attempting to cast something to an object whose type would only be known at run time. C++ does not work this way.

In general, whenever such a situation occurs, nearly all the time the correct solution will involve virtual methods getting invoked on a base class. You will likely need to redesign your classes to use inheritance and virtual methods; using their common base class instead of std::any; then invoking its virtual methods. In some situations std::variant may also work, too.

like image 142
Sam Varshavchik Avatar answered Dec 20 '25 03:12

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!