无法模板<typename>推导出指针类型?

时间:2016-06-18 12:02:52

标签: multithreading templates c++11 promise future

我有以下程序,编译+运行,没问题

#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报告说thread :: thread()ctor找不到合适的重载: 错误:没有匹配函数来调用'std :: thread :: thread(,int *,int *,std :: remove_reference&amp;&gt; :: type)'

是什么消息表明我的模板有什么问题? 如何解决?

感谢。

1 个答案:

答案 0 :(得分:3)

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进行测试