开发者

Using std::function to call a member function while using templates

开发者 https://www.devze.com 2023-01-24 04:48 出处:网络
I have a templated class like this: template <typename T> class AguiEvent { std::vector<std::tr1::function<void(T, AguiWidget*)>> events;

I have a templated class like this:

template <typename T>
class AguiEvent {


std::vector<std::tr1::function<void(T, AguiWidget*)>> events;
public:
void call(AguiWidget* sender, T arg) const;
void addHandler(std::tr1::function<void(T, AguiWidget*)> proc);
void removeHandler(std::tr1::function<void(T, AguiWidget*)> proc);
void removeHandler();
AguiEvent();
};

template <typename T>
void AguiEvent<T>::removeHandler()
{
    if(events.size() > 0)
    {
        events.pop_back();
    }
}


template <typename T>
void AguiEvent<T>::addHandler( std::tr1::function<void(T, AguiWidget*)> proc)
{
    events.push_back(proc);
}


template <typename T>
void AguiEvent<T>::removeHandler(std::tr1::function<void(T, AguiWidget*)> proc)
{
    for(int i = 0; i < events.size(); ++i)
    {
        if(events[i] == proc)
        {
            events.erase(events.begin() + i);
            return;
        }
    }
}


template <typename T>
void AguiEvent<T>::call(AguiWidget* sender, T arg) const
{
    for(size_t i = 0; i < events.size(); ++i)
        events[i](arg,sender);
}

template <typename T>
AguiEvent<T>::AguiEvent()
{
}

However using it like this:

testWidget[count]->eventMouseClick.addHandler(&testWidget[0]->silly);

causes this error:

Error   5   error C2276: '&' : illegal operation on bound member function expression    c:\users\josh\documents\visual studio 200开发者_JAVA百科8\projects\agui\alleg_5\main.cpp   190

I thought std::function allowed this. What am I doing wrong?

Thanks


Assuming that testWidget[0]->silly is a member function with the appropriate signature, it looks like you should be using TR1's bind to specify the object on which the member function will be called:

function<void(T,AguiWidget*)> handler = bind(&TestWidget::silly, testWidget[0], _1, _2);
testWidget[count]->eventMouseClick.addHandler(handler);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号