user3782790 user3782790 - 13 days ago 5
C++ Question

c++11 std::async not working with variadic template parameters by refererence

How it is possible that this code is not working ?
I would like MyThread::run to work with any kind of parameters, and the parameters being passed by reference and not by value.

http://ideone.com/DUJu5M

#include <iostream>
#include <future>
#include <string>

class MyThread {

std::future<void> future;

public:

template<class... Args>
MyThread(Args&&... myArgs) :
future(std::async(std::launch::async, &MyThread::run<Args&&...>, this, std::forward<Args>(myArgs)...))
{}

template<class... Args>
void run(Args&&... myArgs) {}
};

int main() {
std::string x;
MyThread thread(x); // Not working
MyThread thread(10); // Working
return 0;
}


Thanks

Answer

You can use std::ref to pass a reference_wrapper. It will be unpacked automatically by standard library features like std::bind/std::thread or std::async.

int main() {
    std::string x;
    MyThread thread(std::ref(x)); // Not working
    MyThread thread2(10); // Working
    return 0;
}

demo

Comments