Is there an implementation of container classes for C++ which support notification in a similar way as ObservableCollection for C#?
A:
There's no such thing in STL. That doesn't mean that someone hasn't created such a thing in an open source library, but I don't believe it's part of the language.
duffymo
2010-07-06 10:25:26
A:
You will need to write your own, and back it on to your favourite container.
DeadMG
2010-07-06 10:31:39
+1
A:
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
}
Mike Seymour
2010-07-06 11:12:54