2010-07-06 86 views

回答

5

沒有像你描述的標準類,但Boost.Signals是一個相當強大的通知庫。當它改變了我將創建爲發出信號的物體的包裝,沿着這個線路:

#include <boost/signals.hpp> 
#include <vector> 
#include <iostream> 

// Wrapper to allow notification when an object is modified. 
template <typename Type> 
class Observable 
{ 
public: 
    // Instantiate one of these to allow modification. 
    // The observers will be notified when this is destroyed after the modification. 
    class Transaction 
    { 
    public: 
     explicit Transaction(Observable& parent) : 
      object(parent.object), parent(parent) {} 
     ~Transaction() {parent.changed();} 
     Type& object; 

    private: 
     Transaction(const Transaction&); // prevent copying 
     void operator=(const Transaction&); // prevent assignment 

     Observable& parent; 
    }; 

    // Connect an observer to this object. 
    template <typename Slot> 
    void Connect(const Slot& slot) {changed.connect(slot);} 

    // Read-only access to the object. 
    const Type& Get() const {return object;} 

private: 
    boost::signal<void()> changed; 
    Type object; 
}; 

// Usage example 
void callback() {std::cout << "Changed\n";} 

int main() 
{ 
    typedef std::vector<int> Vector; 

    Observable<Vector> o; 
    o.Connect(callback); 

    { 
     Observable<Vector>::Transaction t(o); 
     t.object.push_back(1); 
     t.object.push_back(2); 
    } // callback called here 
} 
0

STL中沒有這種東西。這並不意味着有人沒有在開源庫中創建這樣的東西,但我不相信它是語言的一部分。

-1

您需要自行編寫並將其備份到您喜歡的容器中。

0

我做它的方式我有這樣的事情在我的收藏notify_updatedwait_event,我打電話notify_updated更改後,然後在其他部分我正在等待事件。我的解決方案對於我正在解決的問題非常具體,因此更多的是C-ish。認爲它與Mike的樣本在概念上相似。