In C #:

myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened); void HandleSomethingHappened(string foo) { } 

How to play in a similar tone in C ++? How to create some EventHandler where you can feed the method and then where can you get this method from it? I want to create a class, the object of which could indicate somehow what it would do and not what it would do something with.

  • Can be more specific about "any method"? Is it a member function of a class, as opposed to a regular function? - HolyBlackCat
  • one
    Judging by the question, do you want to call your method on any call to another? Or how to use it? Just store the address of the method in the object and return it? Put the question correctly. - Harry
  • Any method is static and dynamic? With different arguments or with one constant list of arguments? Everything can be done, but we need specifics. - AlexGlebe
  • What is "feed method" and "get back method"? - AnT

2 answers 2

Use the wrapper class Function to store the method, and keep an instance of it in the EventHandler. Regarding the implementation of Function: I do not know how to make an object be called as a function (probably, redefinition of operators). Storage as an object field solves the problem of pulling a method somewhere else.

  • "to force the object to be called as a function" - the operator () is redefined, this class is called a functor. And you can also use the lambda function (which is essentially a functor). True, the vehicle so dullly expressed his wish that it is not clear what he needs at all. - freim

I understand you need something similar, in this example, the class is assigned a pointer to a lambda and the action is executed

 // Example program #include <iostream> class Method { public: Method(int (*fptr)(int, int)) { this->bar = fptr; } void SetFunction(int (*fptr)(int, int)) { this->bar = fptr; } //В данном случае GetFunction это имя функции int (*GetFunction())(int, int) { return this->bar; } private: //Сам наш указатель вообщем то int (*bar)(int, int); }; int main() { //Пример с со сложением Method test ( [](int x, int y) { return x+y; } ); std::cout << test.GetFunction()(10,10) << std::endl; //Пример с умножением test.SetFunction ( [](int x, int y) { return x*y; } ); std::cout << test.GetFunction()(10,10) << std::endl; }