函数指针的映射.被指向的函数必须是静态的吗
Map of function pointers. Does the function being pointed to have to be static?
我昨天才弄清楚函数指针,我正在游戏引擎中实现控制台/命令系统。
我认为,在选择运行命令时要做什么时,使用带有字符串键和函数指针值的映射可以消除对大量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)"
现在我想我知道这意味着什么了。我可以使用一个静态函数来绕过这个问题,但我希望能够引用Game
的特定实例的方法。
然而,函数指针的映射必须能够指向任何具有返回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(); };
您可以在映射中放置一个对象和一个函数指针。然后调用该函数的静态版本,它只调用传入对象上函数的真实版本。您可以在Game
中对任意多个函数重复此操作。
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" );
相关文章:
- enable_if转换构造函数(静态强制转换,is_base_of)
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 有没有一种方法可以使全局函数/静态成员函数一次可呼出
- C++ - 模板类 -> 静态函数 -> 静态函数指针的链接错误
- 获取 llvm::函数静态地址
- 成员函数静态变量与成员变量
- 如何将sqlite3+扩展函数静态链接到C/C++应用程序中
- Visual Studio 2015 Natvis如何显示函数静态变量
- 返回一个指向函数静态数据的指针合适吗
- 如何将函数静态应用于非类型模板包的各个元素并对结果求和
- 是否可以通过编程方式创建函数静态对象
- 函数静态变量析构函数和线程
- 函数静态成员变量
- 隐藏模板化的辅助函数——静态成员或未命名的命名空间
- 这个解决方案对MSVC的双重检查锁定错误和函数静态有什么问题?
- 类成员函数静态和私有
- c++函数静态局部,性能好
- 函数静态变量初始化
- 使用基类中的函数静态地调用纯虚函数的派生类实现
- 使成员函数静态会使程序无法编译。想不通为什么