【问题标题】:no suitable constructor exists to convert from "int()" to "std::function<int()>" [duplicate]没有合适的构造函数可以从“int()”转换为“std::function<int()>”[重复]
【发布时间】:2021-08-16 22:16:03
【问题描述】:

我正在尝试将两个函数 OnUserCreateOnUserUpdate 作为参数传递给另一个应该调用它们的函数。但是,我收到一条错误消息

no suitable constructor exists to convert from "int()" to "std::function&lt;int()&gt;"

这是一个模糊地模仿我的代码的可重现示例。

//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();
    }
}

【问题讨论】:

标签: c++


【解决方案1】:

您正在尝试传递非静态类方法,这些方法需要一个对象实例来调用它们。但是您没有指定该对象。

试试这个:

void Run()
{
    win.ProcessMessage(
        std::bind(&App::OnUserCreate, this),
        std::bind(&App::OnUserUpdate, this)
    );
}

Demo

或者:

void Run()
{
    win.ProcessMessage(
        [this](){ return this->OnUserCreate(); },
        [this](){ return this->OnUserUpdate(); }
    );
}

Demo

【讨论】:

  • 感谢您的回答。对于第二个例子,我不明白为什么[this](){ return this-&gt;OnUserCreate(); } 而不是[this](){ return this-&gt;OnUserCreate; }()不会调用函数吗?
  • 是的,它会,这正是您在这种情况下想要的。您会将 lambda 分配给 std::function。因此,当Run() 调用create()(或update())时,它会先调用lambda,然后再调用OnUserCreate()(或OnUserUpdate())。然后将OnUserCreate()/OnUserUpdate()的返回值作为lambda的返回值,作为create()/update()的返回值(Run()忽略)。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 2020-09-08
相关资源
最近更新 更多