if (functionMap.find(CommandArgument) != functionMap.end())
(this->*(functionMap[CommandArgument]))();
The problem that I am having is this works fine if all the functions are contained in ‘MyClass’ but say I want to call an init function from multiple classes like so:
That's what originally my solution would have been, I was thinking that I could use a BaseClass but I still don't know how I could override that in the functionMap.
Okay, I see how I can do this with an function pointer array, but I don't see how I can invoke it by using a string (Using the map to have functions mapped to strings).
The way you shown me is good, and thank you!
But it's not generic since I still have to call each array directly from its own class too, and it defeats the purpose of why I have the map. (I have the map since I have a bunch of arguments, I don't want to deal with an if statement).
But it's not generic since I still have to call each array directly from its own class too
You could use std::function, then.
1 2 3 4 5 6 7 8
B b;
C c;
std::map<std::string, std::function<void()>> map;
map["f1"] = [&b](){ b.f(); };
map["f2"] = [&c](){ c.f(); };
map["f1"]();
map["f2"]();
Note that the std::functions become uncallable if the bound objects go out of scope, so be careful with that. Alternatively, std::shared_ptr could be used:
1 2 3 4 5 6 7 8
auto b = std::make_shared<B>();
auto c = std::make_shared<C>();
std::map<std::string, std::function<void()>> map;
map["f1"] = [b](){ b->f(); };
map["f2"] = [c](){ c->f(); };
map["f1"]();
map["f2"]();