C++ cast std::any to base class without knowing derived class type

507 Views Asked by At

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));
1

There are 1 best solutions below

1
Deepak Kumar On

Here's how you can convert an object of an unknown derived class to its base class type using std::any_cast and dynamic_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_cast with a pointer to the base class HCallable and then you can use dynamic_cast to safely convert the pointer to the base class pointer type HCallable*.

Here is example you can do something like this :

std::any instance = std::make_any<DerivedClass>();

// Extract derived class object from std::any
auto derivedPtr = std::any_cast<DerivedClass*>(&instance);

// convert the pointer to the base class
HCallable* basePtr = dynamic_cast<HCallable*>(*derivedPtr);

// Check if pointer conversion completed before using basePtr
if (basePtr) {
    // Here you can use basePtr as an HCallable*
} else {
    // error
}