First, let's define a class that others might want to observe:
struct Caller
{
typedef std::function< void() > Callback;
void RegisterCallback( Callback const & callback )
{
callbacks.push_back( callback );
}
void Notify() const
{
std::for_each( callbacks.begin(), callbacks.end(), []( Callback const & callback )
{
callback();
});
}
std::vector< Callback > callbacks;
};
Next, a free function we want to be called:
void GlobalFunction()
{
std::cout << "GlobalFunction" << std::endl;
}
As well as a functor:
struct Functor
{
void operator()()
{
std::cout << "Functor" << std::endl;
}
};
And finally, a member function on an observing class:
struct Observer
{
void Update()
{
std::cout << "Observer::Update" << std::endl;
}
};
Hooking everything up:
Caller caller;
Observer observer;
caller.RegisterCallback( &GlobalFunction );
caller.RegisterCallback( Functor() );
caller.RegisterCallback( std::bind( &Observer::Update, observer ) );
caller.Notify();
Gives the output we'd expect:
GlobalFunction Functor Observer::UpdateBut how could we implement an UnregisterCallback method on the Caller class? std::function is neither LessThanComparable nor EqualityComparable so storing them in a set (ordered or otherwise) won't work. Seems that Boost.Signals might be a better fit for this task.