c++templatesinheritanceboost-signals2

specific class in inheritance hierachy as type in boost::signal2 callback


I'm using a boost::signals2::signal inside a gui-class like this:

class GuiElement {
    //...
    typedef boost::signals2::signal<void(GuiElement &)> GuiElementSignal;
    virtual GuiElementSignal &getSignal() { return signal_; };
}

All gui-classes inherit from this class so that callbacks can be registered. An example with a Toggle class:

toggle.getSignal().connect([](lx::GuiElement &el) {
    // cast to access toggle specific functions
    state = static_cast<lx::Toggle &>(el).state();
    cout << state << endl;
});

Inside the callback function everytime I have to cast GuiElement to a SpecificClass to access the specific class functions. I'd like to avoid this cast and declare the callback signature as: toggle.getSignal().connect([](lx::Toggle &el) {...

Is there a way to realize this with templates with something like typedef boost::signals2::signal<void(T &)> GuiElementSignal where T is replaced with the class?


Solution

  • You can use the curiously recurring template pattern to solve this problem, for example:

    template<typename T>
    class GuiElement {
        //...
        typedef boost::signals2::signal<void(T&)> GuiElementSignal;
        virtual GuiElementSignal &getSignal() { return signal_; };
    };
    
    class Button : public GuiElement<Button> {/* ... */};