The function foo
is declared as:
int foo(int);
It has the function type int(int)
(taking a parameter int
and returning int
).
However, the resulting callable returned by std::bind
when you bind 3
to the first parameter has a different function type: int()
, e.g.:
auto func = std::bind(foo, 3) // Bind 3 to the first parameter.
func(); // Calling func requires no parameter.
Solution
The template parameter specified when declaring the std::packaged_task
should be specified as int()
, e.g.:
std::packaged_task<int()> task{std::bind(foo, 3)};
Alternatively don't bind the parameter to 3
when constructing the std::packaged_task
, instead supply it directly when creating the std::thread
object:
std::packaged_task<int(int)> task{foo}; // Don't bind 3
auto f = task.get_future();
std::thread trd{std::move(task), 3}; // Supply 3 here instead.
std::cout << f.get() << std::endl;
Furthermore
- Make sure to call
trd.join()
before returning from functionmain
. When using
std::thread
also use the sleep function from the Standard Library instead of the non-portablesleep
, e.g.:std::this_thread::sleep_for(std::chrono::seconds(1));
- Also when using
std::move
you should include the header<utility>
in case the other headers don't include it.