In this section, you will learn how you can bind the thread function and its respective arguments with packaged_task.
Let's take the code from the previous section and modify it to understand the bind feature, as follows:
#include <iostream>
#include <future>
#include <string>
using namespace std;
int add ( int firstInput, int secondInput ) {
return firstInput + secondInput;
}
int main ( ) {
packaged_task<int (int,int)> addTask( add );
future<int> output = addTask.get_future();
thread addThread ( move(addTask), 15, 10);
addThread.join();
cout << "The sum of 15 + 10 is " << output.get() << endl;
return 0;
}
The std::bind( ) function binds the thread function and its arguments with the respective task. Since the arguments are bound upfront, there is no need to supply the input arguments 15 or 10 once again. These are some of the convenient ways in which packaged_task can be used in C++.