fin*_*bob 3 c++ static stl function-pointers map
我只是在昨天找到了函数指针,我正在游戏引擎中实现一个控制台/命令系统.
我认为使用带有字符串键的映射和函数指针值将在选择运行命令时要做的事情时消除对大量if语句的需要.
我收到这个错误:
argument of type
"void (Game::*)(std::string prop, std::string param)"
is incompatible with parameter of type
"void (*)(std::string prop, std::string param)"
Run Code Online (Sandbox Code Playgroud)
现在我想我知道这意味着什么.我可以使用静态函数来绕过它,但我希望能够引用特定实例的方法Game.
但是,函数指针的映射必须能够指向具有return void和2个字符串参数的任何函数.
首先这可能吗?
如果没有,是否可以通过静态成员函数修改实例变量?我对此并不抱太大的期望.
任何帮助一如既往地受到赞赏.
函数指针很糟糕.除非你绝对被迫,否则不要使用它们.相反,更喜欢std::function<void(std::string, std::string)>和std::bind/ lambdas.与函数指针不同,它们可以与任何函数对象一起使用,包括绑定的成员函数.
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(); };
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1136 次 |
| 最近记录: |