template不能推导出指针类型吗

C++语言 码拜 8年前 (2016-04-12) 1008次浏览
下面一个例子程序,编译运行没有问题。

#include <thread>
#include <future>
#include <iostream>
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
}

就会编译不过,说thread::thread构造函数找不到这样的重载。
error: no matching function for call to “std::thread::thread(<unresolved overloaded function type>, int*, int*, std::remove_reference<std::promise<int>&>::type)”
这个错误是什么含义? 本人的模板用法不对吗?
谢谢。

解决方案

40

需要显式指定:

#include <iostream>
#include <numeric>
#include <thread>
#include <future>
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); 
}
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<int*>, std::begin(numbers), std::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
    return 0;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明template不能推导出指针类型吗
喜欢 (0)
[1034331897@qq.com]
分享 (0)