view raw
val val - 9 months ago 48
C++ Question

Converting future in multithreaded library

I am using a simple multithreaded library to try and understand the basics.

The lib has a queueing function that looks like this:

auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;

And stores functions like this:

std::queue< std::function<void()> > tasks;

There was an example on how to pass Lambdas, but i'd like to pass member variables. So i created a small object:

Threadpool tp(4);

class myClass{
vector<std::future<int>> res;
int compute(int i){
return 2 * i;
void update(){
for(int i = 0; i < 10; i++){
// C2664 - 'std::future<int>::future(const std::future<int> &)':
// cannot convert argument 1 from 'std::future<_Rx>' to 'std::future<int> &&'
tp.enqueue(std::bind(&myClass::compute, this), i)

Creating an argumentless function works. But even the example lambda on the site works with a passed parameter:

tp.enqueue([](int answer) { return answer; }, 42);

What am I not getting here?

Also a side question: When it comes to standard functions what is the advantage of using:

auto fn(...) -> return type

instead of:

return type fn(...)


Placeholders is missing:

tp.enqueue(std::bind(&myClass::compute, this, std::placeholders::_1), i);

or simply

tp.enqueue(std::bind(&myClass::compute, this, i));

or with lambda

tp.enqueue([=]() { this->compute(i); });