Let suppose several child classes for a base class:
class Base
{
public:
void printHello() const { cout << "Hello" << endl; }
};
class Child1: public Base {};
class Child2: public Base {};
class Child3: public Base {};
..
class ChildN: public Base {};
Let suppose a variant containing any of the contained classes:
using MyVariant = std::variant<Base, Child1, Child2, Child3, ... ChildN>;
Note: The interest of this (compared to a simple vector of polymorphic pointers), is to have all the data in the same memory array, because they are going to be transferred to a device. In this case, the real content of each object is in the vector, not only a pointer to some
heapposition.
Finally, let suppose I want to work with the Base polymorphic version of each element of a vector<MyVariant>.
std::vector<MyVariant> myVariantList;
... // Initialization
for (const MyVariant& elem: myVariantList)
{
const Base* baseElem = get_if_polymorph<Base>(elem); //HOW TO?
baseElem->printHello();
}
Note: Obviously, the trivial solution of having an
ifstatement for each types is not the intention, because new child classes could be added toMyVariantwithout having to change all further usages. (Extensibility)
So another way to express the question is:
How to manage polymorphism within std::variant?