A bit of an obscure issue here but I need a way to cast std::any to its base class, without knowing what derived class it is.
In other words, given a base class:
struct HCallable {
int numArgs;
std::vector<std::type_info> argTypes;
virtual std::any call(std::vector<std::any> args)=0;
};
And an instance of one of its (numerous) derived classes:
class in : public HCallable {
public:
int numArgs=1;
std::any call(std::vector<std::any> args) {
std::cout << huff::anyToString(args[0]);
std::string result;
std::getline(std::cin, result);
return result;
}
};
std::any instance = std::any(new in());
How can I take this instance, and convert it into an object of type HCallable without knowing that instance has type in.
This code works if only I can find a way not to explicitly state in*:
HCallable* func = dynamic_cast<HCallable*>(std::any_cast<in*>(instance));
Here's how you can convert an object of an unknown derived class to its base class type using
std::any_castanddynamic_cast.First, you need to extract the stored pointer to the derived class object from std::any. You can do this by using
std::any_castwith a pointer to the base classHCallableand then you can use dynamic_cast to safely convert the pointer to the base class pointer typeHCallable*.Here is example you can do something like this :