observable container for C++

There is no standard class like you describe, but Boost.Signals is quite a powerful notification library. I would create a wrapper for objects that raises a signal when it is changed, along the lines of this:

#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
}

Tags:

C++