【发布时间】:2021-08-17 21:09:33
【问题描述】:
我不知道如何将带有 lambda 参数的方法传递给 std::thread。 我的代码示例如下:
using namespace std;
#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <thread>
template<typename var>
void show(int a, var pf)
{
for(int i = 0; i < 10; pf(i))
{
cout << "i = " << i << endl;
}
}
int main()
{
int int_test = 10;
auto func = [](int &x)->int{ return x = x + 1; };
show(10, func);
std::thread a(&show, 10, func);
a.join();
}
使用命令编译:
g++ ThreadLambda.cpp -pthread -std=c++11 -o test;
并且错误显示:
ThreadLambda.cpp:149:66: error: no matching function for call to ‘std::thread::thread(<unresolved overloaded function type>, int, main()::<lambda(int&)>)’
std::thread a(&show, 10, [](int &x)->int{ return x = x + 1; });
【问题讨论】:
-
#include
#include #include #include using namespace std;模板 void show(int a, var pf) { for(int i = 0; i int{ return x = x + 1; };显示(10,函数); std::thread a(&show, 10, func); a.join(); }
标签: c++ multithreading c++11