2

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.

Bfyuvf
  • 139
  • 9
  • It is not possible. The best you can do, if the design allows it, is to generate the cast from the same template argument as the original object. But that is often not possible. `std::any` is not nearly as useful as it first appears. Consider using `std::variant` instead if it works for your case. – François Andrieux May 30 '22 at 14:14
  • From what I saw, std::variant also requires a cast-like thing with a required type – Bfyuvf May 30 '22 at 14:16
  • The `std::variant` is a template which "knows" all the types which it may contain. Which of them is currently in an instance is internally stored. Thus, an instance of `std::variant` "knows" the cast to perform (or the branch to apply) depending on its contents. – Scheff's Cat May 30 '22 at 14:19

1 Answers1

4

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148