如何将 std::bind 与 std::function 一起使用以便将方法作为回调传递?

Ale*_*nko 0 c++

我在 SO 上找到了这个答案

/sf/answers/2866120351/

我在回答中做了一切,但我收到一个错误

有我的代码

我需要传递回调的方法

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

我的回调实现

void TV_DepthCamAgent::progress_callback(int count, int copied_file)
{
...
}
Run Code Online (Sandbox Code Playgroud)

用法

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

    shared::Utils::copy_files(callback, path_from_copy, path_to_copy);
...
}
Run Code Online (Sandbox Code Playgroud)

我得到了一个错误

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

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

我究竟做错了什么?

Jar*_*d42 5

你错过了占位符:

auto callback = std::bind(&TV_DepthCamAgent::progress_callback,
                          this,
                          std::placeholders::_1,
                          std::placeholders::_2);
Run Code Online (Sandbox Code Playgroud)

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

auto callback = [this](int count, int copied_file){
     return this->progress_callback(count, copied_file);
};
Run Code Online (Sandbox Code Playgroud)