vendredi 4 mai 2018

Calling private function in lambda from outside the class

In my current project I am trying to pass a private member function as parameter to another function. In my code, the other function is a member function of a different class, but for keeping it simple, here it is a free function.

void outside_function(std::function<void(int)> func) {
  // do something with func
}


class MyClass {
public:
  void run();

private:
  bool my_func(double); // defined in source file
};

Now, from inside run I want to put my_func into outside_function as argument. Since the signature of run does not fit the requirements for the parameter, I cannot simply pass it. Using the adapter pattern was my first try, which was when I was reminded that member functions implicitly take the this pointer as first argument. This answer suggests using a lambda expression, which is what I did.

void MyClass::run() {
  outside_function([this](int a) -> void {
    double d = static_cast<double>(a);
    this->my_func(d);
  });
}

Why does this work? From my point of understanding, outside_function does not have access to my_func. Why don't I have to make my_func public first? Is it something the compiler does or some C++ rule I don't know?

Additionally, are there any catches to this approach that might break my code?

Aucun commentaire:

Enregistrer un commentaire