3

packaged_task で非同期を実装しようとしています。テンプレート化された関数 bsync を使用してこれを試みています。bsync は、関数 f とパラメータ パック args の 2 つの引数を取り、future を返します。future は f(args...) によって返される型です。つまり、リターンは未来です

私はほとんどそこにいると思いますが、型変換エラーが発生しています。どんな助けでも大歓迎です:

#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;
}
4

1 に答える 1

3

末尾の戻り値の型が正しくありません。あなたが持っている:

future<result_of<decltype(f)&(Args&&...)>>

それはfuturewith タイプresult_of<...>です。実際の結果の型を生成するには、メタ関数を実際に評価する必要があります。result_ofあれは:

future<typename result_of<Fn(Args&&...)>::type>
       ^^^^^^^^^                        ^^^^^^

typenameそれを修正すると、typedeffor にa がありませんA

于 2015-05-04T16:02:46.860 に答える