std::vector of std::function
Asked Answered
D

1

3

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?

Desouza answered 13/12, 2010 at 15:30 Comment(0)
C
0

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.

Cycloparaffin answered 13/12, 2010 at 15:57 Comment(1)
Thanks for this. I guess my main concern is how to generate that ID on the fly. I want the readability of using the += to pass a function/lambda in to the event vector. So I guess the wrapper class needs to generate the ID based on the function passed. Perhaps the address of it?Desouza

© 2022 - 2024 — McMap. All rights reserved.