Search code examples
c++argument-passingstdthreadinline-functions

How to write lambda function with arguments? c++


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


Solution

  • 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.