c++ - 如何从函数指针调用非静态方法?

标签 c++

我有一个“Person”类,如下所示:

typedef void (*action)();
typedef std::unordered_map<int, action> keybindMap; // maps keycodes to functions

class Person {
    keybindMap keybinds;
    void doSomething();
}

我用它在正确的时间调用函数:

iter = keybinds.find(event.key.keysym.sym); // event.key.keysym.sym is the key code
if (iter != keybinds.end())
{
    (*iter->second)(); // call whatever function that key is bound to.
}

为了绑定(bind)按键,我使用了keybinds.insert_or_assign(SDLK_a, doSomething)。但是,这不起作用(因为 doSomething 是非静态的)。如何更改绑定(bind)代码和/或 (*i​​ter->second)() 部分,以便我可以调用与 person.doSomething 等效的内容?

最佳答案

非静态方法需要一个对象来调用它。普通的函数指针没有空间来保存对象的引用。

如果您将映射更改为保存 std::function,则可以使用 std::bind() 或 lambda 将对象与方法关联起来指针,例如:

using action = std::function<void()>;
using keybindMap = std::unordered_map<int, action>;

class Person {
    keybindMap keybinds;
    void doSomething();
};

... 

Person p, otherP; //must outlive the map...
p.keybinds[...] = [&otherP](){ otherP.doSomething(); } 

...

iter = keybinds.find(event.key.keysym.sym);
if (iter != keybinds.end()) {
    iter->second();
}

另一方面,如果所有目标方法都在同一个类/对象中,则可以使用普通方法指针而不是 std::function,这会减少一些开销,例如:

class Person {
    using action = void (Person::*)();
    using keybindMap = std::unordered_map<int, action>; 

    keybindMap keybinds;
    void doSomething();
};

... 

keybinds[...] = &Person::doSomething;

...

iter = keybinds.find(event.key.keysym.sym);
if (iter != keybinds.end()) {
    (this->*(iter->second))();
}

关于c++ - 如何从函数指针调用非静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71029221/

相关文章:

c++ - 字符串函数在这里是什么意思

c++ - C/C++多线程程序使用rand_r的正确方法

c++ - 如何将用户从控制台输入的内容读入 Unicode 字符串?

c++ - 使用 C++ 在我的应用程序的菜单栏中创建一个 "Save Current Setting"功能

c++ - c或c++中是否有任何头文件来实现图形,树等数据结构?

c++ - Xcode 新手 : Don't understand compiler error message

c++ - 添加初始化列表的元素

c++ - 检测容器是否具有迭代器类型

c# - 我可以在 C++ 中创建一个类似于 C# 的全局命名空间层次结构来帮助开发人员使用我们的代码吗?

c++ - 如何使用 CMake 将外部库( boost )包含到 CLion C++ 项目中?