Search code examples
c++lambda

Is it possible to counstruct anonymous function inside of member function in such way that the parameter passed to the function is "this" object?


I would like to construct anonymous-function inside of member-function of Class called Semaphore, the anonymous function takes one parameter of type "Semaphore" and the Object that should be passed is the current object calling the Method aquire(), is something like this possible and if it is possible is it considered a good style?

Consider following Code:

void Semaphor::aquire() {
    std::unique_lock<std::mutex> lock(mtx);
    //while because of spurious wakeup (OS Wakup)
    //while (numOfRessources == 0) {
        //condVar.wait(lock);
    //}
    is there any way to do the followig, so that s is "this" Object
    condVar.wait(lock, [](Semaphor s) { return s.isNumOfRessourcesZero(); });
    numOfRessources--;
}

Solution

  • Is this what you are looking for ?

    #include <iostream>
    
    class Test {
    
      void Hello(const char* name) {
        std::cout << "Hello " << name << std::endl;
      }
    public:
      void DoSomething() {
        auto fFunc = [this](const char* name) {
          Hello(name);
        };
        fFunc("Marcus");
      }
    };
    
    int main()
    {
      Test a;
      a.DoSomething();
    }