简体   繁体   中英

Callback function member of polymorphic class

I am making a User Interface and the two primary classes are UIControl and UIView . Both are abstract classes. Each view in the UI, such as the main menu etc. have UIView as parent class. I want these derived view classes to be able to assign their own member functions as callbacks for the controls. How can this be achieved?

Psuedocode below:

class UIControl
{
public:
    void (*m_callback_click)(int button_index, int x, int y);

    // This class also statically calls callback_click if a control is clicked
}

class UIView
{
    // Abstract class
}

class UIMainMenu : public UIView
{
public:
    UIControl* m_button1;

    void initialize();
    void button1_click(int button, int x, int y);
}

void UIMainMenu::initialize()
{
    m_button1 = new UIControl();

    m_button1->m_callback_click = &button1_click;
}

You'll need to change

    static void button1_click(int button, int x, int y);
 // ^^^^^^

to get this to compile.

Another possibility is to declare a member function pointer in the UIControl class, like

 void (UIView::*m_callback_click)(int button_index, int x, int y);

Also ,- as @Joachim Pileborg sugessted -, prefer to manage a std::function object instead of holding a raw function pointer. As mentioned you can use std::bind to assign it properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM