【发布时间】:2021-08-16 22:16:03
【问题描述】:
我正在尝试将两个函数 OnUserCreate 和 OnUserUpdate 作为参数传递给另一个应该调用它们的函数。但是,我收到一条错误消息
no suitable constructor exists to convert from "int()" to "std::function<int()>"
这是一个模糊地模仿我的代码的可重现示例。
//ERROR IN LINE win.ProcessMessage(OnUserCreate, OnUserUpdate);
#include <functional>
class Window
{
public:
//std::function<int()> creates a function that returns int and takes
//no parameter...or so i read not sure if this is right either
void ProcessMessage(std::function<int()> create, std::function<int()> update)
{
create();
update();
}
};
class App
{
private:
Window win;
private:
int OnUserCreate()
{
return 1;
}
int OnUserUpdate()
{
return 1;
}
public:
void Run()
{
win.ProcessMessage(OnUserCreate, OnUserUpdate);
}
};
int main()
{
App app;
while (true)
{
app.Run();
}
}
【问题讨论】:
-
你只能用全局函数这样做。当您使用类的方法时,您需要使用
std::bind- 请参阅stackoverflow.com/questions/7582546/…
标签: c++