Member variable as template paramter

Started by
6 comments, last by Juliean 9 years, 11 months ago

Hello,

is it possibly to write a templated class whos template decides which member variable of the class to being used? My problem is as follows: I have a gui with slots of signals, which is just a templated class. There are signals like for release, click, hover, etc... These are all generic for that special case, e.g. the release signal returns not values to the caller function. However, often I would like to hand over additional data, e.g. the number of the button that has just been pressed from a specific key-bar in game. I don't want to make this part of the gui widgets themselfs, so I wrote a wrapper-class:


template<typename Data, typename WidgetType=Widget>
class DataContainer
{
public:

    DataContainer(void) : m_data(Data()), m_pWidget(nullptr)
    {
    }

    DataContainer(WidgetType& widget, Data data) : m_data(data), m_pWidget(&widget)
    {
        widget.SigReleased.Connect(this, &DataContainer::OnAccessData);
    }

    DataContainer(const DataContainer<Data, WidgetType>& container): m_data(container.m_data), m_pWidget(container.m_pWidget),
        SigAccess(container.SigAccess)
    {
        m_pWidget->SigReleased.Connect(this, &DataContainer::OnAccessData);
    }

    DataContainer(DataContainer<Data, WidgetType>&& container) : m_data(container.m_data), m_pWidget(container.m_pWidget),
        SigAccess(std::move(container.SigAccess))
    {
        m_pWidget->SigReleased.Disconnect(&container, &DataContainer::OnAccessData);
        m_pWidget->SigReleased.Connect(this, &DataContainer::OnAccessData);
        container.m_pWidget = nullptr;
    }

    ~DataContainer(void)
    {
        if(m_pWidget)
            m_pWidget->SigReleased.Disconnect(this, &DataContainer::OnAccessData);
    }

    void SetWidget(WidgetType* pWidget)
    {
        if(m_pWidget && pWidget != m_pWidget)
            m_pWidget->SigReleased.Disconnect(this, &DataContainer::OnAccessData);

        if(pWidget)
            pWidget->SigReleased.Connect(this, &DataContainer::OnAccessData);

        m_pWidget = pWidget;
    }

    WidgetType* GetWidget(void) const
    {
        return m_pWidget;
    }

    WidgetType* operator->(void) const
    {
        return m_pWidget;
    }

    DataContainer<Data>& operator=(const DataContainer<Data> container)
    {
        m_data = container.m_data;
        m_pWidget = container.m_pWidget;
        SigAccess = container.SigAccess;

        m_pWidget->SigReleased.Connect(this, &DataContainer::OnAccessData);
    }

    void OnAccessData(void)
    {
        SigAccess(m_data);
    }

    core::Signal<Data> SigAccess;

private:

    Data m_data;
    WidgetType* m_pWidget;
};

This allows me to instead hook the SigAccess, which will return some user-defined data. The problem is, that this class only works for the SigRelease, and I would have to rewrite it for every other signal that there possibly is.

To come back to my question, is there any possiblity to solve this using templates? I want to be able to do e.g.


gui::DataContainer<SigClicked, UserData, Window> container(*pWindow); // SigClicked => name of the signal to being clicked in the widget class, always a spezialization of "core::Signal<Args...>"
Advertisement
This might set you in the right direction:

template <
    typename ClassName,
    typename MemberType,
    MemberType ClassName::*MemberPointer
>
MemberType get(ClassName* self)
{
    return self->*MemberPointer;
}

struct Foo
{
    int bar;
};

int main()
{
    Foo foo;
    foo.bar = 0;
    return get<Foo, int, &Foo::bar>(&foo);
}

Sean Middleditch – Game Systems Engineer – Join my team!


This might set you in the right direction:

You are right, this set me right on track. However, I've run into another issue along the way. Problem is, I also need the core::Signal<> template arguments to forward them in case the signal is called. So right now, the templated class definition looks like this:


template<typename Data, typename WidgetType, typename SignalType, SignalType Widget::*Signal, typename... Args>

My main two regards here are:

- This makes it attrocious to define those DataContainers. I'm already using typedefs as soon as I use one, but now I have to write e.g:


typedef DataContainer<unsigned int, Button, core::Signal<>, &Button::SigReleased> ButtonContainer;

To get such a container to work. And this is just in case an empty signal is used. Consider


typedef DataContainer<unsigned int, Window, core::Signal<unsigned int, unsigned >, &Window::SigDrag, unsigned int, unsigned int> WindowContainer;

Yuk! Is there any way to "configure" the template so that I only have to supply the "&Widget::Signal"-part and have him deduce the other template parameters automaticall? I had one solution in mind:


template<typename Data, typename WidgetType, typename... Args, core::Signal<Args...> WidgetType::*Signal>

This however won't even compile, since "Args" must be at end of the template list, and if I put it there, of course args isn't defined in "core::Signal<Args...>". Any workaround or other way to accomplish such an auto-deduction here?

- I'm having problems with derived classes. Say my base "Widget"-class defines the Signal "SigReleased", and I'm using


template<typename WidgetType, core::Signal<> WidgetType::*Signal>
class Test
{
}


Test<Window, &Window::SigReleased>; // compile error

Then it will complain about how SigReleased is not a member of window. Which in fact forces me to add yet ANOTHER template parameter to the list, in case I want to use a signal of a derived class. Holy ....! Again, do you know of any workaround/solution for this?

EDIT:

The simplest & dumbest solution that came in mind for the first issue was just to pass in a direct pointer to the Signal in the ctor of the class, and having only the variadic signal arguments in the template argument list... but that sucks too, potentially breaking the intent of the class (now I can pass in different signals / I can even pass signals from other widgets)... so any real solution would be highly prefered!

In this case, you're probably just better off using std::function or something similar and binding (partly) at runtime instead of compile time. Then you use functions and type deduction instead needing to spell out member function signatures as much.

On my phone or I'd make an example; look up std::function and "type erasure" for more info.

Sean Middleditch – Game Systems Engineer – Join my team!

Yes, std::function is surprisingly easy to use for things like these:


class ButtonWidget
{
    std::function<void()> _onClick;

public:
    void SetOnClick(std::function<void(int buttonNumber)> action) { _onClick = action; }

private:
    void TrackClick()
    {
        // ...
        if (_onClick)
            _onClick(buttonNumber);
        // ...
    }
};

And set up the action:


buttonWidget->SetOnClick([](int buttonNumber) {
    switch (buttonNumber)
    {
        ...
    }
});

openwar - the real-time tactical war-game platform

Am I correct in the assumption that in your suggestion, I would have to rework the whole Signal-system of my gui, or did Felix Ungman's class naming (ButtonWidget) throw me off? I wouldn't really want to change how things work internally, the gui-libary is already quite large with a lot of code depending on it, if I really had to rework all the systems that would be a heck ton of work. Or did I misunderstand, and I can just use std::function for the DataContainer-wrapper-class?

Ok, the example maybe didn't illustrate what I meant, a better one might be:


class ButtonWidget
{
    std::function<void()> _onClick;

public:
    void SetOnClick(std::function<void()> action) { _onClick = action; }

private:
    void TrackClick()
    {
        // ...
        if (_onClick)
            _onClick();
        // ...
    }
};

Then you can fix the data you want to hold in the lambda:


for (int i = 0; i < n; ++i) {
    int buttonNumber = i;
    button[i]->SetOnClick([buttonNumber]() {
       ButtonWasClicked(buttonNumber);
    }
});

Code is simple but powerful. I don't know how it relates to your framework or how you would need to rewrite it (it seems you use signals both for events and for data bindings, right?), but I've found the technique very useful in my own gui code.

openwar - the real-time tactical war-game platform

Ah, I think I see now. I'm really unsure how I can use this for my framework really, though. Actually, I'm using signals merely for events, data binding is actually needed only in certain cases, which I designed this DataContainer-class for, I didn't want to "overload" the signals/event handling stuff with "instance"-data stuff, since in most cases its used like "Class A has two buttons, where each of them will call a different callback when clicked". There is only certain cases now like in my visual scripting editor, where I have a arbitrary number of inputs/outputs, that should, on right-click, all call the same method, but be destinquishable, so that I can say e.g. output-slot 2 has been clicked, make a connection here. I think I'll look more into std::function given the code you have posted and see how I can apply this... but having it as a seperate layer over all other widgets is a main requirement, I like the way how simple the signals work for gui code, especially for registering multi-output:


class Widget
{
public:

      core::Signal<> SigReleased;
}

void Widget::OnRelease(...)
{
    // ....
    SigRelease();
    // ....
}


// somewhere in code
Widget* pWidget = CreateWidget();
pWidget->SigReleased.Connect(this, &SomeClass::OnReleased); // this can happen for as many times as wanted

I'll see what it can do so far. Thanks anyways, though I'm still open for any suggestion for improving the template-class like I put it in my second post, it was actually kind of working minus those quadrillion paramters I had to specify.

This topic is closed to new replies.

Advertisement