2010-12-13 27 views
3

我有以下幾點:的std ::性病載體::功能

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容器中?我需要把它包裝在別的東西嗎?

回答

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_ S等)。

另一種可能性是存儲boost::function s的標籤,客戶端將記憶和使用,以確定在刪除其特定的功能。

+0

感謝。我想我主要關心的是如何即時生成該ID。我希望使用'+ ='將函數/ lambda傳入事件向量的可讀性。所以我想包裝類需要根據傳遞的函數生成ID。也許它的地址? – 2010-12-13 16:03:14