user3782790 user3782790 - 4 months ago 24
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.

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

class MyThread {

std::future<void> future;


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;



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;