2016-06-18 49 views
1

我有以下程序,編譯運行+,沒有問題無法模板<typename>推演指針類型?

#include <thread> 
#include <future> 
#include <iostream> 
#include <algorithm> 
void f(int* first, 
     int* last, 
     std::promise<int> accumulate_promise) 
{ 
    int sum = std::accumulate(first, last, 0); 
    accumulate_promise.set_value(sum); // Notify future 
} 

int main() 
{ 
    int numbers[] = { 1, 2, 3, 4, 5, 6 }; 
    std::promise<int> accumulate_promise; 
    std::future<int> accumulate_future = accumulate_promise.get_future(); 
    std::thread work_thread(f, begin(numbers), end(numbers), 
          std::move(accumulate_promise)); 
    accumulate_future.wait(); // wait for result 
    std::cout << "result=" << accumulate_future.get() << '\n'; 
    work_thread.join(); // wait for thread completion 
} 

但是,如果我改變 「F」 成模板:

template<typename Iterator> 
void f(Iterator first, 
     Iterator last, 
     std::promise<int> accumulate_promise) 
{ 
    int sum = std::accumulate(first, last, 0); 
    accumulate_promise.set_value(sum); // Notify future 
} 

然後失敗編譯,GCC報告線程::螺紋()構造函數無法找到正確的過載: 錯誤:調用 '的std ::螺紋::線程(,INT *,詮釋*,性病:: remove_reference &> ::型)'

沒有匹配的功能是什麼是指示的消息興錯了我的模板? 如何解決它?

謝謝。

回答

2

f是一個模板。

std::thread work_thread(f, begin(numbers), end(numbers), 
         std::move(accumulate_promise)); 

爲了把它放在鬆散的術語,std::thread的第一個參數是一個函數指針或東西的作用就像一個函數指針。它不會將模板作爲第一個參數。

模板在實例化時變成類或函數。模板在使用時會被實例化。所以,給定這個模板定義,並以這樣的方式使用它:

f(something.begin(), something.end(), some_kind_of_a_promise); 

這個實例化一個模板,並使用它。要明確地實例化模板,而不使用它:

f<int *> 

現在,您在此處有一個實例化的模板。下面的作品在這裏:

std::thread work_thread(f<int *>, std::begin(numbers), 
         std::end(numbers), 
         std::move(accumulate_promise)); 

用gcc 5.3.1測試