3
\$\begingroup\$

Building on the answer in C++ class member callback simple examples, I've tried to put together a simple subject-observer pattern without needing to inherit a virtual Observer class. I also wanted to isolate most of the C++11 funny stuff within the Subject. bind and function are little-used features, so keeping the number of uses low should reduce opportunities for programmer errors.

Example class name Subject. Callback for this example takes one bool argument. In Subject declaration:

public:
    template<class T> void addCallback(T* object, void(T::*mf)(bool))
    {
        callbacks_.emplace_back(std::bind(mf, object, std::placeholders::_1));
    }
private:
    std::vector<std::function<void(bool)>> callbacks_;

In Observer declaration (class name for example Observer):

    void nameDoesntMatter(bool);

In Subject implementation, to call observers:

for (const auto& cb: callbacks_)
    cb(booleanValue);

In Observer implementation, to register callback, assuming sub points to the Subject class in question:

sub->addCallback(this, &Observer::nameDoesntMatter);

Seems pretty simple. Seems to work ok.

Questions:

  1. How can I alter this so that an observer can remove its registration with the subject?
  2. If I'm worried about speed, is there a significant difference between the traditional virtual base class implementation of this pattern and the one described here?
  3. Did I make a mistake in my implementation?
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.