Observable container for C ++

Is there an implementation of container classes for C ++ that support notification just like ObservableCollection for C #?

+5
source share
4 answers

There is no standard class as you describe, but Boost.Signals is a pretty powerful notification library. I would create a wrapper for objects that raise a signal when it changes, line by line:

#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
}
+5
source

There is no such thing in STL. This does not mean that someone did not create such a thing in the open source library, but I do not consider it part of the language.

0
source

How do I do I have something like notify_updatedand wait_eventin my collection, and I call notify_updatedafter the change, and then in other parts of the waiting events. My solution is very specific to the problem I am solving, therefore it is more than C-ish. Thought it was like Mike's concept.

0
source

You will need to write your own and back to your favorite container.

-1
source

All Articles