For this post, I wanted to implement a callback in C++.
A method I have does some work (copying files) which might take minutes to complete and whilst copying the files it posts updates back to the callback telling the calling method of the progress, i.e. the file that’s being copied.
The code for the method which takes a callback looks like this, notice we’re using the std::function to wrap our callback
void Update( std::vector<UpdateInfo*>& updates, std::function<void(std::tstring&, std::tstring&)> callback) { // does something and then calls the following callback(item->source, item->destination) }
To create the call we use
std::function<void(std::tstring&, std::tstring&)> f = std::bind(&MyClass::NotifyUpdate, this, std::placeholders::_1, std::placeholders::_2); Update(f);
the _1, _2 are placeholders, allowing us to alter the values from the caller at a later time (i.e. from the Update method in this case). The std::bind method allows us to wrap a function ptr and an instance of the class containing the callback (the NotifyUpdate method).