How to write lambda function with arguments? c++
Asked Answered
U

3

6

I want to call a method (for this example std::thread constructor) with lambda function, passing int value:

int a=10;

std::thread _testThread = thread([a](int _a){
  //do stuff using a or _a ?
});
_testThread.detach();

I don't know how to properly write such function, I get this error: C2064: term does not evaluate to a function taking 0 arguments

Upbow answered 27/8, 2014 at 21:7 Comment(4)
You will have to capture _a, as you capture a.Garvey
well I need just 'a' inside that thread.Upbow
Thats a lambda functionSalesgirl
The why do you have a parameter called _a?Garvey
L
15

std::thread takes a callable object as well as any arguments to pass to it. If you give no arguments, std::thread will try to call that object with no arguments, hence the error.

If you need a parameter:

std::thread _testThread{[a](int _a) {
    std::cout << a << ' ' << _a; //prints main's a, followed by somethingThatWillBe_a
}, somethingThatWillBe_a};

If you're just trying to use main's a, it's already captured:

std::thread _testThread{[a] {
    std::cout << a; //prints main's a
}};

I would also recommend being super careful if you think you need to detach a thread. If there's any possibility of joining the thread instead, go for it.

Lantha answered 27/8, 2014 at 21:10 Comment(0)
B
5

You can access int a in one of two ways. Either pass it in as a parameter to the thread's constructor or capture it in the lambda's closure:

int a=10;

// pass in a as a parameter
std::thread _testThread1([](int _a){

  //do stuff using a or _a ?

}, a); // pass a to the parameter _a
_testThread1.detach();

// capture a in the closure
std::thread _testThread2([a](){ // capture a

  //do stuff using a or _a ?

});
_testThread2.detach();
Bloomers answered 27/8, 2014 at 21:15 Comment(0)
C
4

If you only want to pass some value to lambda function, look at my code below:

int main()
{
    int a = 10;

    [](int arg)
    {
        cout << "arg = " << arg << endl;
    }
    (a);

    return 0;
}

If you want to make thread with lambda function and passing to it some arguments see next code example:

int main()
{
    int a = 10;

    thread thd([](int arg) { cout << "arg = " << arg << endl; }, a);

    thd.join();

    return 0;
}
Confect answered 27/8, 2014 at 21:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.