【问题标题】:How to use std::bind with std::function in order to pass method as a callback?如何将 std::bind 与 std::function 一起使用以将方法作为回调传递?
【发布时间】:2020-03-22 19:19:37
【问题描述】:

我在 SO 上找到了这个答案

https://stackoverflow.com/a/40944576/5709159

我做了一切都像在回答,但我得到一个错误

这是我的代码

我需要传递回调的方法

/*static*/ void Utils::copy_files(std::function<void(int, int)> progress_callback,
        std::string const & path_from,
        std::string const & path_to)
    {
....
    }

我的回调实现

void TV_DepthCamAgent::progress_callback(int count, int copied_file)
{
...
}

用法

void TV_DepthCamAgent::foo()
{
...
auto callback = std::bind(&TV_DepthCamAgent::progress_callback,
        this);

    shared::Utils::copy_files(callback, path_from_copy, path_to_copy);
...
}

我得到一个错误

SE0312 不存在从“std::_Binder”到“std::function”的合适的用户定义转换

错误 C2664 'void shared::Utils::copy_files(std::function,const std::string &,const std::string &)':无法将参数 1 从 'std::_Binder' 转换为 'std ::函数'

我做错了什么?

【问题讨论】:

  • 错误消息与提供的代码不一致。为了消除歧义,我建议调整呈现的代码以使其匹配。也许制作一个minimal reproducible example 以便将问题简化为您可以更轻松地进行试验的东西。

标签: c++


【解决方案1】:

你错过了占位符:

auto callback = std::bind(&TV_DepthCamAgent::progress_callback,
                          this,
                          std::placeholders::_1,
                          std::placeholders::_2);

但更简单的是,IMO 是使用 lambda:

auto callback = [this](int count, int copied_file){
     return this->progress_callback(count, copied_file);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多