该程序使用Visual Studio编译,但clang和gcc无法完成

时间:2018-03-28 14:34:14

标签: c++ multithreading clang

这是我的代码:

#include <iostream>
#include <future>
#include <thread>
#include <vector>

using namespace std;

vector <int> exec(vector <int> &a, vector <int> &b) {
vector <int> res = a;
res.push_back(b[0]);
res.push_back(b[1]);
res.push_back(b[2]);
res.push_back(b[3]);
return res;
}


int main() {


vector <int> a1{ 1, 2, 3, 4 }, a2{ 5, 6, 7 , 8  };

std::packaged_task<vector <int>(vector <int>, vector <int>)> task(exec);
std::future<vector <int>> ret = task.get_future();            
std::thread th(std::move(task), a1, a2);  

th.detach();

vector <int> P1 = ret.get();


for (auto i = 0; i < P1.size(); ++i) {
    cout << P1[i];
}
cout << endl;


system("pause");
return 0;
}

使用-std = c ++ 17或-std = c ++ 14 Clang总是抛出一个错误:

In file included from Source.cpp:2:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\future:568:6: error: no
matching constructor for initialization of 'function<std::vector<int,
std::allocator<int> > (std::vector<int, std::allocator<int> >, std::vector<int,
std::allocator<int> >)>'
: _Fn(_Fnarg)
  ^   ~~~~~~

它也引发了一些警告。 g ++也是如此。我使用Visual Studio 2015和clang 6.0.0。怎么了?

2 个答案:

答案 0 :(得分:1)

您需要packaged_task种匹配函数类型。特别是,因为我假设你想保留exec的引用:

std::packaged_task<vector<int> (vector<int>&, vector<int>&)> task(exec);
std::future<vector <int>> ret = task.get_future();            
std::thread th(std::move(task), std::ref(a1), std::ref(a2));  

答案 1 :(得分:0)

您的exec函数会引用向量,但您可以使用向量的副本来定义您的任务和未来。可以更改exectask定义。

我建议将exec类型更改为:

std::vector<int> exec(std::vector<int> base, std::vector<int> const &b) {
    base.push_back(b[0]);
    base.push_back(b[1]);
    base.push_back(b[2]);
    base.push_back(b[3]);
    return base;
}

task

std::packaged_task<std::vector<int>(std::vector<int>, std::vector<int> const&)> task(exec);