Is it possible to define anonymous member function in C ++

I have a funny use case for my small pet project where I would like to have

static map<std::string, pointer-to-member-function> 

      

in the class. It's easy if the syntax is a little cumbersome, and it works nicely.

What I would like to do is also have the pointer-to-member function be a simple lambda expression in my static initializer. This would make it sooo easy to package things like this in a nice macro.

I want the member pointer function to have access to the private members of the class, so I cannot use a normal lambda with "this" as a parameter. However, I can't seem to find a way to define the anonymous member function - C ++ lambdas seem to be free global functions?

+3


source to share


1 answer


Once you have it std::function<void(const MyClass&)>

in your map, you can store a lambda that takes an instance of your class as a parameter. As long as the lambda is defined in the member function MyClass

, it will be able to access the private members of the class MyClass

:

#include <map>
#include <functional>

class MyClass {
private:
  void myPrivate() const { }
public:
  static std::map<std::string, std::function<void(const MyClass&)>> funcs;

  static void initFuncs() {
    funcs["test"] = [](const MyClass& mc) { mc.myPrivate(); };
  }
};

std::map<std::string, std::function<void(const MyClass&)>> MyClass::funcs;

int main() {
  MyClass::initFuncs();
  MyClass mc;
  MyClass::funcs["test"](mc);    
}

      



Live demo .

+3


source







All Articles