1

I don't know how to pass the method with a lambda parameter into the std::thread. My code sample as below:

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

Compile with the command: g++ ThreadLambda.cpp -pthread -std=c++11 -o test;

And the error show:

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; template 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(); } – Khanh Le Van May 30 '21 at 07:45
  • See [Why should I not #include ?](https://stackoverflow.com/q/31816095) and [Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721). – prapin May 30 '21 at 12:38

2 Answers2

1

show is a template so you need to provide the template arguments before you can take a pointer to it:

std::thread a(&show<decltype(func)>, 10, func);
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • @KhanhLeVan Note that in your question you claimed that you did not know how to pass a method **with a lambda parameter** into something. It turned out that you did not know how to pass **a templated entitiy** into that something (the lambda was fine). Let that be a warning against jumping to conclusions, especially when debugging. Be wary of focusing on one thing to the point where you are blind to alternatives. – JaMiT May 31 '21 at 02:11
0

Another variant:

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