lundi 4 mai 2015

c++: Building async with packaged_task

I am attempting to implement async with a packaged_task. I am attempting this via a templated function, bsync. bsync takes 2 arguments: a function,f, and a parameter-pack, args, and returns a future, fut. The future is of the type returned by f(args...). Ie - the return is future

I think I am almost there, but I am getting a type-conversion error. Any help would be appreciated:

#include "stdafx.h"
#include <iostream>
#include <future>
#include <thread>
#include <functional>
#include <type_traits>
using namespace std;


//Implement bsync as a templated function
//Template parameters are (i) Fn (the function to run), (ii) Args, a parameter pack of arguments to feed the function
//The function returns a future<Ret>, where Ret is the return-type of Fn(Args)
template<class Fn,class...Args>
auto bsync(Fn f, Args&&...args)->future<result_of<decltype(f)&(Args&&...)>>{

    //Determine return-type
    typedef result_of<decltype(f)&(Args&&...)>::type A;

    //Initialize a packaged_task
    packaged_task <A(Args&&...)>tsk(f);

    //Initialize a future
    future<A> fut = tsk.get_future();

    //Run the packaged task in a separate thread
    thread th(move(tsk),(args)...);

    //Join the thread
    th.join();

    return fut;
}

int plus_one(int x){
    cout << "Adding 1 to " << x << endl;
    return x++;
}

int main(){
    auto x = bsync(plus_one, 1);

    cout << "Press any key to continue:" << endl;
    cin.ignore();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire