简体   繁体   中英

How to use std::bind with std::function in order to pass method as a callback?

I found this answer on SO

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

I made everything like in answer, but I get an error

there is my code

Method where I need to pass my callback

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

My callback implementation

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

Usage

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

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

There is an error that I get

SE0312 no suitable user-defined conversion from "std::_Binder" to "std::function" exists

Error C2664 'void shared::Utils::copy_files(std::function,const std::string &,const std::string &)': cannot convert argument 1 from 'std::_Binder' to 'std::function'

What am I doing wrong?

You miss placeholders:

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

but simpler, IMO, is to use lambda:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM