Good way to implement used callbacks in C ++

I have a custom menu class written in C ++. To split the code into easy-to-read functions, I use callbacks.

Since I don't want to use singletones for the menu host, I provide another parameter (target) that will be passed to the callback as the first parameter (some kind of workaround for the missing "this" link).

Registration-Signature

AddItem(string s, void(*callback)(void*,MenuItem*), void* target = NULL)

Registration Example

menu->AddItem(TRANSLATE, "translate", &MyApp::OnModeSelected);

Handler example

/* static */
void MyApp::OnModeSelected(void* that, MenuItem* item) {
    MyApp *self = (MyApp*)that;
    self->activeMode = item->text;
}

Is there anything that could be considered dirty with this approach? Maybe better?

+5
source share
7 answers

, , . - . boost:: function :

typedef boost::function<void (MenuItem*)> callback_type;
AddItem(const std::string& s, const callback_type& callback = callback_type());

boost:: bind boost:: lambda :

menu->AddItem("Open", boost::bind(&MyClass::Open, this));

- boost:: , .

+10

. , " OO" :

class IMenuEntry {
public:
    virtual void OnMenuEntrySelected(MenuItem* item) = 0;
};

AddItem(string s, IMenuEntry * entry);

class MyApp : public IMenuEntry {
public:
    virtual void OnMenuEntrySelected(MenuItem* item){
        activeMode = item->text;
    }
}

" " this.

+8

boost:: bind.

menu->AddItem(TRANSLATE, 
              "translate", 
              boost::bind( &MyApp::OnModeSelected, this, _1, _2 ));
+3

, , . observer.

+1
+1

Read this white paper. He creates various methods for the callback mechanism, analyzing performance, usability, and other trade-offs in fairly detailed information. It seemed to me that it is difficult to read: - (

+1
source

You can use functor to encapsulate your callback. This will allow you to use the C-style function or object interface to provide a callback.

0
source

All Articles