I want to use some kind of container in cpp to store custom classes. Not existing objects of the classes, but the class as datatype.
sth like:
vector<????>{int,double,string,bool...}
or in my case:
vector<????>{class1,class2,class3 ...}
Eventually I want to iterate through the container to create an object of each class in it:
for(??? c:myVector){
c* tmp = new c();
Edit: I just realized, I would have to store the different object-pointers somewhere to access them later, so even then would have to write every single one manually. That might be the reason, why its not possible to archive. I'm still curious if there is a way, so if you know one, enlighten me please.
CodePudding user response:
If set of accepted classes is fixed, you might use something like:
std::vector<std::variant<std::type_identity<class1>,
std::type_identity<class2>,
std::type_identity<class3>,
std::type_identity<class4>
>
> vec{std::type_identity<class1>{}, std::type_identity<class4>{}};
for (const auto& var : vec) {
std::visit([](auto typ){ using classX = typename decltype(type)::type; /*..*/}, var);
}
CodePudding user response:
You may or may not want to do something like this:
class base { ... };
class class1 : public base { ... };
class class2 : public base { ... };
class class3 : public base { ... };
using pbase = std::unique_ptr<base>;
std::vector<std::function<pbase(void)>> objectCreation =
{ []()->pbase { return std::make_unique<class1>(); },
[]()->pbase { return std::make_unique<class2>(); },
[]()->pbase { return std::make_unique<class3>(); } };
Note that the array stores functions (function objects in this case) not types orr classes or anything of the sort. Classes are not objects and cannot be stored.
Note also that all functions return pointers (smart pointers in this case) to a common base class of your objects. You work with the objects via ther virtual functions defined in the base class and overridden in the derived classes.
pbase pb = objectCreation[1]();
pb->doMyStuff(); // virtual func defined in Base
This is one of the ways we deal with the "I don't know the exact type of this thing but I need to work with it anyway" problem. Inheritance, virtual functions, pointers or references. Those are the three pillars of the object-oriented way. There are other ways but I recommend getting up to speed with this one first.
For additional reading, do a web search for "creational design patterns". You should get some links that mention "factories". That's the good stuff.