2015-05-01 59 views
1

我试图将packaged_task包装在泛型类中,但无法用泛型函数初始化它。我已经得到它为特定的工作,但我希望它更抽象。只是一个fyi,如果你取消注释了我注释掉的两行代码,代码运行良好。我的猜测是,我试图错误地使用模板参数。完美转发和packaged_task包装

编辑:做了一些补充,以便实际工作,但同样的问题仍然存在。所以,如果我尝试将一个函数传递给我的类的ctor,那么当我尝试调用ret.get()时,会出现“不良函数调用”。不过,如果我直接命名该函数,它就可以工作。编辑2.0:为了使这很容易,我想知道这里是所有调用tsk(func)不起作用,和tsk(倒计时)呢?如何使TSK(FUNC)工作...

int countdown (int from, int to) { 
    for (int i=from; i!=to; --i) { 
     std::cout << i << '\n'; 
     std::this_thread::sleep_for(std::chrono::seconds(1)); 
    } 
    std::cout << "Lift off!\n"; 
    return from-to; 
} 

template<typename> class packaged_task_wrapper; 

template<typename T, typename... Args> 
class packaged_task_wrapper<T(Args...)> { 
public: 

    template<typename ...Ts> 
    explicit packaged_task_wrapper(Ts &&... ts) : func(forward<Ts>(ts)...) { 

     packaged_task<T(Args...)> tsk(func);  // THIS DOES NOT WORK 
     //packaged_task<T(Args...)> tsk(countdown); // THIS WORKS 

     future<T> ret = tsk.get_future();   // get future 
     thread this_thread (move(tsk),3,0);  // spawn thread to count down from 3 to 0 
     int value = ret.get();      // wait for the task to finish and get result 
     // ... 

     cout << "The countdown lasted for " << value << " seconds.\n"; 
     this_thread.join(); 
    } 
}; 


int main() 
{ 
    packaged_task_wrapper<int(int,int)>(countdown); 

    return 0; 
} 

回答

1

为什么不使用std::async?如果你想要的是在不同的线程上运行该函数,那么这将做到这一点。

auto future_result = std::async(std::launch::async, 
           [&](){ return countdown(3, 0); }); 
future_result.get(); 

如果你不想异步这样,就可以使用:

template<typename> class packaged_task_wrapper; 

template<typename T, typename... Args> 
class packaged_task_wrapper<T(Args...)> { 
public: 

    template <typename F> 
    explicit packaged_task_wrapper(F&& f) { 

     packaged_task<T(Args...)> task(std::forward<F>(f)); 
     future<T> ret = task.get_future();  // get future 
     thread this_thread (move(task), 10, 8); // spawn thread to count down from 3 to 0 
     T value = ret.get();      // wait for the task to finish and get result 
     // ... 

     std::cout << "The countdown lasted for " << value << " seconds.\n"; 
     this_thread.join(); 
    } 
}; 
+1

因为我故意不使用异步。也许我应该稍微调整标题。 –

+0

这不起作用。让我回到我第一次遇到的同样的错误。 –

+1

你是如何创建实例的?适用于:'packaged_task_wrapper 任务(&倒计时);' –