函数指针的映射.被指向的函数必须是静态的吗

Map of function pointers. Does the function being pointed to have to be static?

本文关键字:函数 静态 指针 映射      更新时间:2023-10-16

我昨天才弄清楚函数指针,我正在游戏引擎中实现控制台/命令系统。

我认为,在选择运行命令时要做什么时,使用带有字符串键和函数指针值的映射可以消除对大量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" );