2015-05-01 64 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 任務(&倒計時);' –