【问题标题】:std::vector of std::functionstd::vector 的 std::function
【发布时间】:2010-12-13 15:30:14
【问题描述】:

我有以下几点:

  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 容器中吗?我需要用别的东西包起来吗?

【问题讨论】:

    标签: function vector c++11 visual-c++-2010


    【解决方案1】:

    您可以将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_(例如,两个不同的EventFuns 将有不同的id_s,等等)。

    另一种可能性是将boost::functions 与客户端会记住的标签一起存储,并用于识别删除它时的特定功能。

    【讨论】:

    • 谢谢。我想我主要关心的是如何动态生成该 ID。我希望使用+= 将函数/lambda 传递给事件向量的可读性。所以我猜包装类需要根据传递的函数生成ID。也许是它的地址?
    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    相关资源
    最近更新 更多