I am attempting to develop a way in C++ to determine if a pointer to a class with virtual methods is a particular type of subclass using some form of RTTI.
Here are some example classes:
class Base {
public:
virtual void foo() = 0;
};
class A : public Base {
public:
void foo() override;
};
class B : public Base {
public:
void foo() override;
};
class BB : public B {
public:
};
My goal is to determine the type of an instance of the root class (in this example Base) and use this to "route" this instance to a particular "handler" function. For example, I would have a table of std::type_index and std::function pairs. If the run-time type of the class passed in matches a type in the table, it calls the associated function with that instance.
Ideally, this would work using any level of inheritance. For example, using the classes above, let's say I have the following (conceptual) table
Type | Function
---------------
A | fooA()
B | fooB()
If I pass in an instance of the BB class (as a Base*), it should be "routed" to fooB because BB is a subclass of B.
In my research, I found the following: How do I check if an object's type is a particular subclass in C++? where the accepted answer says "You really shouldn't." However, in my case, I don't see another way to do this.
I hope that this makes sense. Please let me know if there is a better way to think about/achieve what I am trying to do.
Thanks