开发者

std::vector of std::function

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 i开发者_运维问答t up in something else?


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜