gpt4 book ai didi

c++ - 传递非静态成员函数作为函数的参数

转载 作者:行者123 更新时间:2023-11-30 03:27:24 25 4
gpt4 key购买 nike

我需要将一个非静态成员函数传递给一个参数

class Foo {
void f() {}
void caller() {
//calling of g() happens here using f()
}
};

Class Goo {
std::map<int,std::vector<std::function<void()>>>> m;
void g(int i, std::function<void()> const& h) {
m[i].push_back(h);
}
}

我试着打电话g(f), g(Foo::f), g(std::make_fn(Foo::f), g(std::make_fn(Foo:f, this), g(this.f)并且还尝试将其作为引用传递(尽管它应该)。
我得到的错误是非静态成员函数的无效使用。

编辑:我在 g()

后面添加了功能

最佳答案

您必须解决的问题是this 参数对于非静态成员函数是隐式的。这意味着如果你想稍后调用成员函数,你还需要传递指向对象的指针。

其中一种方法是使用 std::bind(&Foo::f, this)

更新 1您可以使用 smart pointersFoo 的生命周期与 std::bind 创建的仿函数的生命周期联系起来。

class Foo : std::enable_shared_from_this<Foo> {
void f() {}
void caller() {
// CAVEAT! shared_from_this() will work iff instance of `Foo` is already owned
// by an std::shared_ptr. This means that when you create `Foo`
// you must do so via std::make_shared<Foo>()
g(std::bind(&Foo::f, shared_from_this()));
}
};

这就是如何将 Foo 的生命周期绑定(bind)到通过 std::bind 生成的 std::function 的生命周期。

请参阅代码注释中的警告。

更新 2您的仿函数 vector 不正确。

std::map<int,std::vector<std::function<void()>const&>> m;

必须是

std::map<int,std::vector<std::function<void()>>> m;

(没有常量引用)

关于c++ - 传递非静态成员函数作为函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47430782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com