将成员函数和lambdas传递给std :: function

时间:2017-02-26 04:31:47

标签: c++ function events std-function

我尝试创建控件/窗口事件,类似于在C#的Windows窗体/ WPF中完成的操作。每个事件类都包含一个参数类型,并传递它以及指向发送对象的指针。使用lambda函数时,这一切都很好,但是当我尝试向事件添加成员函数时,我得到C2276 '&': illegal operation on bound member function expressionC2660 'Event<MouseButtonEventArgs>::add': function does not take 1 arguments的编译错误。

如何创建一个可以从任何类中获取lambda函数和成员函数的事件类(无论该类是&#34; sender&#34;)?

Event.h

template<class Args> struct EventListener {

    /* The function type to be called by the event. */
    typedef function<void(ControlBaseSPtr, Args&)> ArgsFunction;
    string name;
    ArgsFunction function;
};

template<class Args> class Event {

    /* The function type to be called by the event. */
    typedef function<void(ControlBaseSPtr, Args&)> ArgsFunction;
    deque<EventListener<Args>> listeners;

    Event(EventDirections direction) {
        this->direction = direction;
    }

    void add(const string& name, ArgsFunction function) {
        EventListener<Args> listener = EventListener<Args>(name, function);
        for (auto it = listeners.begin(); it != listeners.end(); it++) {
            if (it->name == name) {
                throw exception("Event::operator+= listener already exists in the event");
            }
        }
        listeners.push_back(listener);
    }

    //...
};

Control.h

class ControlBase {
    Event<MouseEventArgs> _eventMouseMovedGlobal;
    Event<MouseButtonEventArgs> _eventMouseButtonGlobal;

    ControlBase();

    void onMouseMovedGlobal(ControlBaseSPtr sender, MouseEventArgs e);
};

Control.cpp

ControlBase::ControlBase() {
    // Works
    _eventMouseButtonGlobal.add("some name", [](ControlSPtr control, MouseButtonEventArgs e){
        //...
    };

    // Doesn't work
    _eventMouseMovedGlobal.add("some name", bind(&onMouseMovedGlobal, this, placeholders::_2))
    // Doesn't work
    _eventMouseMovedGlobal.add("some name", bind(&onMouseMovedGlobal, this))
}

void ControlBase::onMouseWheelGlobal(ControlBaseSPtr sender, MouseWheelEventArgs e) {
    //...
}

1 个答案:

答案 0 :(得分:0)

好吧,由于onMouseMovedGlobal有2个输入参数,因此在创建活页夹时需要占位符或值。所以,而不是

_eventMouseMovedGlobal.add("some name", bind(&onMouseMovedGlobal, this, placeholders::_2))

你需要

_eventMouseMovedGlobal.add("some name", bind(&ControlBase::onMouseMovedGlobal, this, placeholders::_1, placeholders::_2))