1

I'm using a macro I've got from Hazel Engine (TheCherno Youtube channel) to bind a function to a callback in my Button class. It works, but I don't understand this code at all and it's pretty annoying.

Here's the code I'm uncomfortable with :

#define BIND_BUTTON_FN(fn) [this](auto&&... args) -> decltype(auto) { return this->fn(std::forward<decltype(args)>(args)...); }

To be honest, i really don't understand a single keyword in this macro... "decltype", "->" in this context, "...". I don't understand the goal of std::forward, and I don't understand the meaning of the [] operator at the beginning of the macro.

Where I'm using it :

MenuState::MenuState(std::shared_ptr<sf::RenderWindow> window) : State(window)
{    
    m_Buttons["Play"] = std::make_shared<Button>(window);
    m_Buttons["Settings"] = std::make_shared<Button>(window);

    m_Buttons["Play"]->setCallbackFn(BIND_BUTTON_FN(MenuState::launchGame));
    m_Buttons["Settings"]->setCallbackFn(BIND_BUTTON_FN(MenuState::launchSettings));
}

In Button.h (cleaned a bit for readability) :

#define BIND_BUTTON_FN(fn) [this](auto&&... args) -> decltype(auto) { return this->fn(std::forward<decltype(args)>(args)...); }

class Button : public Widget
{
    using CallbackFn = std::function<void()>;
public: //Constructors
    Button(std::shared_ptr<sf::RenderWindow> window);

public: //Public methods    
    void setCallbackFn(const CallbackFn& fn) { m_Callback = fn; }

protected: //Protected attributes
    CallbackFn m_Callback;
    virtual void onClicked() override
    {
        if(m_Callback != NULL) m_Callback();
    }
};

I would easily do a callback for a non-member function by using a function pointer, but when it comes to class member functions, binding a callback function becomes pretty difficult for me to understand.

Thanks a lot for reading ! :)

0 Answers0