Callbacks from a class method (C++)

和自甴很熟 提交于 2020-01-16 09:00:56

问题


I have a Button class. When I click this button, it's selected() method is called.

//Button.cpp
void Button::selected(){
//Do Something
}

//Player.cpp
void Player::Jump(){
//Jump!
}

I also have a Player class. I wanted to make it so that when I click the button, the player method's Jump() is called. I suppose I could just link the Player class with the button. But then I realized that the button class is going to have many other uses, and not just letting my player jump. (ie: a menu selector? make the player move? etc.)

So I was thinking of including some kind of a callback, but I'm not too familiar with them and I'm having trouble understanding some tutorials I've read.

Could someone show me how I would use the selected() method to take in any function/method as a parameter and execute it in the method body?


回答1:


Here's a functor approach where you pass a function as an argument:

template <typename functor_t>
void Button::selected(functor_t func){
  // ...
  func();
  // ...
}

The argument can be a function pointer, or a function object:

 struct functor {
   void operator()() {
     // stuff
   }
 };

 void function() {
   // stuff
 }

Calling a void method() using pointer to member:

struct foo {
  void bar() {
    std::cout << "hello";
  }
};

template <typename class_t>
void function(class_t& c, void (class_t::* mp)()) {
  (c.*mp)();
}

foo x;
function(x, &foo::bar);


来源:https://stackoverflow.com/questions/8275742/callbacks-from-a-class-method-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!