I've only just yesterday figured out function pointers, and I am implementing a console/command system in a game engine.
I figured using a map with a string key and function pointer value would eliminate the need for a huge list of if statements when choosing what to do when running the commands.
I'm getting this error:
argument of type
"void (Game::*)(std::string prop, std::string param)"
is incompatible with parameter of type
"void (*)(std::string prop, std::string param)"
Now I think I know what this means. I could use a static function to get round this, but I want to be able to reference a method of a specific instance of Game.
However the map of function pointers must be able to point to any function with return void and 2 string parameters.
Firstly is this possible?
If not, is it somehow possible to modify instance variables through a static member function? I don't have high hopes for this.
Any help is appreciated as always.
Function pointers are the suck. Don't ever use them unless you're absolutely forced to. Instead, prefer std::function<void(std::string, std::string)> and std::bind/lambdas. Unlike function pointers, these can work with any function object, including a bound member function.
std::unordered_map<std::string, std::function<void()>> command_map;
Game game;
Help helper;
command_map["quit"] = [] { exit(); };
command_map["play"] = [&] { game.play(); };
command_map["help"] = [&] { helper.help(); };
You can put an object and a function pointer in the map. Then call a static version of the function which just calls the real version of the function on the object passed in. You can repeat this for as many functions in Game as you like.
class Game
{
void yourFunc1(std::string prop, std::string param)
{
// do stuff
}
void yourFunc1_static(Game* g, std::string prop, std::string param)
{
g->yourFunc1( prop, param );
}
};
struct MapEntry
{
Game* game;
void (*func)(std::string prop, std::string param);
};
std::map<key_type, MapEntry> _map;
...
_map[key].func( game, "prop", "param" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With