packaged_task示例问题?斯特劳斯特鲁普示例修改



我正在尝试修改 Stroustrup C++第 4 版第 122 页中给出的示例,以直接使用迭代器调用累加器(( 函数。 专门删除*double的使用并使用迭代器。

到目前为止,我有这个,但是它有我不明白的编译问题。

有没有人对完成此操作有任何指示?

#include <iostream>
#include <memory>
#include <thread>
#include <numeric>
#include <vector>
#include <future>
using namespace std;
double comp2(vector<double>& v) {
using Task_type = double(vector<double>::iterator,
vector<double>::iterator, double);
packaged_task<Task_type> pt0 {accumulate};
packaged_task<Task_type> pt1 {accumulate};
#if 0
future<double> f0 {pt0.get_future()};
future<double> f1 {pt1.get_future()};
double *first = &v[0];
// move required bc package_task cannot be copied
thread t1 {move(pt0), first, first + v.size()/2, 0};
thread t2 {move(pt1), first + v.size()/2, first + v.size(), 0};
t1.join();
t2.join();
return f0.get() + f1.get();
#endif
}
int main(int argc, char *argv[])
{
vector<double> v = {1.0, 1.0, 1.0, 1.0};
cout << "v: " << comp2(v) << endl;
return 0;
}

错误是:

g++ -lpthread -pedantic -Wall test87.cc && ./a.out
test87.cc: In function ‘double comp2(std::vector<double>&)’:
test87.cc:13:43: error: no matching function for call to ‘std::packaged_task<double(__gnu_cxx::__normal_iterator<double*, std::vector<double> >, __gnu_cxx::__normal_iterator<double*, std::vector<double> >, double)>::packaged_task(<brace-enclosed initializer list>)’
packaged_task<Task_type> pt0 {accumulate};
^
In file included from test87.cc:6:
/usr/include/c++/8/future:1528:2: note: candidate: ‘template<class _Allocator> std::packaged_task<_Res(_ArgTypes ...)>::packaged_task(std::allocator_arg_t, const _Allocator&, std::packaged_task<_Res(_ArgTypes ...)>&&)’
packaged_task(allocator_arg_t, const _Allocator&,
^~~~~~~~~~~~~
/usr/include/c++/8/future:1528:2: note:   template argument deduction/substitution failed:
test87.cc:13:43: note:   candidate expects 3 arguments, 1 provided
packaged_task<Task_type> pt0 {accumulate};
std::accumulate

不是函数,而是函数模板。要构造packaged_task,你需要给它传递一个具体的函数,像这样:

packaged_task<Task_type> pt0 {accumulate<vector<double>::iterator, double>};
packaged_task<Task_type> pt1 {accumulate<vector<double>::iterator, double>};

您还应该将迭代器而不是指针first,因为不能保证迭代器是作为指针实现的。

auto first = v.begin();

这是一个演示。

最新更新