std::vector of std::function

£可爱£侵袭症+ 提交于 2019-12-02 01:32:12

问题


I have the following:

  typedef std::function<void(const EventArgs&)> event_type;

  class Event : boost::noncopyable
  {
  private:
   typedef std::vector<event_type> EventVector;
   typedef EventVector::const_iterator EventVector_cit;
   EventVector m_Events;

  public:
   Event()
   {
   }; // eo ctor

   Event(Event&& _rhs) : m_Events(std::move(_rhs.m_Events))
   {
   }; // eo mtor

   // operators
   Event& operator += (const event_type& _ev)
   {
    assert(std::find(m_Events.begin(), m_Events.end(), _ev) == m_Events.end());
    m_Events.push_back(_ev);
    return *this;
   }; // eo +=

   Event& operator -= (const event_type& _ev)
   {
    EventVector_cit cit(std::find(m_Events.begin(), m_Events.end(), _ev));
    assert(cit != m_Events.end());
    m_Events.erase(cit);
    return *this;
   }; // eo -=
  }; // eo class Event

And during compilation:

1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm(41): error C2451: conditional expression of type 'void' is illegal
1>          Expressions of type void cannot be converted to other types

Now, I understand this is because of what is being stored in the vector and the operator ==. Is there another way to store std::function in an STL container? Do I need to wrap it up in something else?


回答1:


You can store boost::function in the vector, provided you don't use std::find. Since you seem to need this, wrapping the function in its own class with equality would be probably the best.

class EventFun
{
  int id_;
  boost::function<...> f_;
public:
  ...
  bool operator==(const EventFun& o) const { return id_==o.id_; } // you get it...
};

Note that this requires you maintain the id_ in a sane way (eg. two different EventFuns will have different id_s, etc.).

Another possibility would be to store boost::functions with a tag the client would remember and use to identify the particular function on deleting it.



来源:https://stackoverflow.com/questions/4430425/stdvector-of-stdfunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!