【问题标题】:g++ TestCpp.cpp -pthread -std=c++11 -o test;g++ TestCpp.cpp -pthread -std=c++11 -o 测试;
【发布时间】: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; });

【问题讨论】:

标签: c++ multithreading c++11


【解决方案1】:

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

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

【讨论】:

  • 感谢艾伦 Birtles!现在可以了!再次感谢!
  • @KhanhLeVan 请注意,在您的问题中,您声称您不知道如何将带有 lambda 参数的方法传递给某些东西。事实证明,您不知道如何将 模板化实体 传递给那个东西(lambda 很好)。让这成为对草率下结论的警告,尤其是在调试时。小心不要只专注于一件事,以至于对其他选择视而不见。
【解决方案2】:

另一种变体:

#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();
}

【讨论】:

  • 是的。很好。谢谢,谢尔盖·亚历山德罗维奇。容易理解。
猜你喜欢
  • 2016-07-08
  • 1970-01-01
  • 2015-08-16
  • 2014-02-21
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
相关资源
最近更新 更多