std::vector of std::function

3

我有以下内容:

  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

在编译期间:

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

现在,我明白这是由于向量中存储的内容和运算符 == 导致的。有没有其他方法可以将 std::function 存储在 STL 容器中?我需要将其包装在其他东西中吗?

1个回答

0

你可以将boost::function存储在向量中,只要不使用std::find。既然你似乎需要这个功能,那么将函数包装在自己的类中并实现相等性可能是最好的选择。

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

请注意,这需要您以合理的方式维护id_(例如,两个不同的EventFun将具有不同的id_等)。
另一个可能性是使用客户端将记住并用于标识特定函数的标签存储boost::function

谢谢。我想我的主要关注点是如何即时生成那个ID。我希望使用+=来传递一个函数/lambda到事件向量中,以便提高可读性。因此,我想包装类需要根据传递的函数生成ID。也许是它的地址? - Moo-Juice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接