微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

g++ TestCpp.cpp -pthread -std=c++11 -o test;

如何解决g++ TestCpp.cpp -pthread -std=c++11 -o test;

我不知道如何将带有 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,[](int &x)->int{ return x = x + 1; });

解决方法

show 是一个模板,因此您需要先提供模板参数,然后才能获取指向它的指针:

std::thread a(&show<decltype(func)>,10,func);
,

另一种变体:

#include <iostream>
#include <thread>
#include <functional>

void show(int N,std::function<void(int&)> pf)
{
    for(int i = 0; i < N; pf(i))
    {
        std::cout << "i = " << i << std::endl;
    }
}

int main()
{
    int int_test = 10;
    auto func = [](int &x)->int{ return x = x + 1; };
    show(int_test,func);
    std::thread a(&show,int_test,func);
    a.join();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。