Std :: vector functions std ::

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 at compile time:

 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 that this is due to what is stored in the vector and the == operator. Is there a way to store std::function in an STL container? Does it need to be wrapped with something else?

+3
source share
1 answer

You can save boost::function in vector if you are not using std::find . Since you seem to need this, including a function in your class with equality would probably be 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 maintaining id_ reasonable way (for example, two different EventFun will have different id_ s, etc.).

Another possibility is to save boost::function with a tag that the client will remember and use to identify a specific function when it is deleted.

0
source

Source: https://habr.com/ru/post/887044/


All Articles