I didn’t know exactly how to title this question. I have a base class and two inheriting classes:
class Base {};
class Action : public Base {};
class Title : public Base {};
Now let’s say I have two functions that return either Action * or Title *:
Action *getAction() { return new Action; }
Title *getTitle() { return new Title; }
Is there any way to put these two functions into a map? Like so:
int main()
{
std::map<std::string, Base *(*)()> myMap;
myMap["action"] = getAction;
myMap["title"] = getTitle;
return 0;
}
Right now I’m getting an error:
invalid conversion from `Action* (*)()' to `Base* (*)()'
I could change the signature of the functions to always return the base class, and then it would work, but I’m wondering if there is another way to get around this.
If you use:
then you will not get this error.
std::functionis a polymorphic function pointer wrapper provided by the STL.Of course, using templates, you could write your own function wrapper that stores a target, passes forward arguments and does conversion. This has already been done though, and you should seriously consider carefully before you decide to roll your own. Unless you enjoy reinventing wheels or have very special requirements.