I know what functors are and when to use them with std algorithms, but I haven\'t understood what Stroustrup says about them in the C++11 FAQ.
Can anyon
One of the main use of std::function and std::bind is as more generelized function pointers. You can use it to implement callback mechanism. One of the popular scenario is that you have some function that is going to take long time to execute but you don't want to wait for it to return then you can run that function on separate thread and give it a function pointer that it will callback after it completes.
Here's a sample code for how to use this:
class MyClass {
private:
//just shorthand to avoid long typing
typedef std::function TCallback;
//this function takes long time
void longRunningFunction(TCallback callback)
{
//do some long running task
//...
//callback to return result
callback(result);
}
//this function gets called by longRunningFunction after its done
void afterCompleteCallback(float result)
{
std::cout << result;
}
public:
int longRunningFunctionAsync()
{
//create callback - this equivalent of safe function pointer
auto callback = std::bind(&MyClass::afterCompleteCallback,
this, std::placeholders::_1);
//normally you want to start below function on seprate thread,
//but for illustration we will just do simple call
longRunningFunction(callback);
}
};