In C++ is there a way to pass a type (e.g. a class) as parameter to a function?
Explanation why I need this: There is a abstract data class and a manager class. The manager class contains a list (or in this case a map) of objects of derived classes of data. I use unique_ptr for this as mentioned in the answer of this question.
class Data{}; // abstract
class Manager
{
map<string, unique_ptr<Data>> List;
};
Now imagine I want to add a new data storage to the manager.
class Position : public Data
{
int X;
int Y;
}
How could I tell the manager to create a object of that type and refer an unique_ptr to it?
Manager manager;
manager.Add("position data", Position);
In this case I would need to pass the class Position to the add function of the manager class since I don’t want to have to first create an instance and then send it to the manager.
And then, how could I add the object of that class to the List?
I am not sure if there is a way of doing that in C++. If that can’t be done easily I would really like to see a workaround. Thanks a lot!
You can use templates. In each type deriving from
Datayou will have to define a ‘creator’ function, which have the following prototype:Derived* create(). It will be called internally (you can also return aunique_ptr, but that would requires more memory).Ex:
The
Addmethod will be:Then you use it like this:
EDIT
You can also get rid of the
createfunctions, by using thisAddmethod:Advantage: less code in data structure code.
Inconvenient: data structures have less control on how they’re built.