Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading