I’m aware of the tutorial at boost.org addressing this: Boost.org Signals Tutorial, but the examples are not complete and somewhat over simplified. The examples there don’t show the include files and some sections of the code are a little vague.
Here is what I need:
ClassA raises multiple events/signals
ClassB subscribes to those events (Multiple classes may subscribe)
In my project I have a lower-level message handler class that raises events to a business class that does some processing of those messages and notifies the UI (wxFrames). I need to know how these all might get wired up (what order, who calls who, etc).
Boost like QT provides its own implementation of signals and slots. Following are some example of its implementation.
Signal and Slot connection for namespace
Consider a namespace called GStreamer
Here is how to create and trigger the signal
Signal and Slot connection for a Class
Consider a Class called GSTAdaptor with function called func1 and func2 with following signature
Here is how to create and trigger the signal
When compiling MattyT's example with newer boost (f.e. 1.61) then it gives a warning
So either you define BOOST_SIGNALS_NO_DEPRECATION_WARNING to suppress the warning or you could easily switch to boost.signal2 by changing the example accordingly:
Did you look at boost/libs/signals/example ?
Here is an example from our codebase. Its been simplified, so I don't guarentee that it will compile, but it should be close. Sublocation is your class A, and Slot1 is your class B. We have a number of slots like this, each one which subscribes to a different subset of signals. The advantages to using this scheme are that Sublocation doesn't know anything about any of the slots, and the slots don't need to be part of any inheritance hierarchy, and only need implement functionality for the slots that they care about. We use this to add custom functionality into our system with a very simple interface.
Sublocation.h
Sublocation.C
Slot1.h
Slot1.C
The code below is a minimal working example of what you requested.
ClassA
emits two signals;SigA
sends (and accepts) no parameters,SigB
sends anint
.ClassB
has two functions which will output tocout
when each function is called. In the example there is one instance ofClassA
(a
) and two ofClassB
(b
andb2
).main
is used to connect and fire the signals. It's worth noting thatClassA
andClassB
know nothing of each other (ie they're not compile-time bound).The output:
For brevity I've taken some shortcuts that you wouldn't normally use in production code (in particular access control is lax and you'd normally 'hide' your signal registration behind a function like in KeithB's example).
It seems that most of the difficulty in
boost::signal
is in getting used to usingboost::bind
. It is a bit mind-bending at first! For a trickier example you could also usebind
to hook upClassA::SigA
withClassB::PrintInt
even thoughSigA
does not emit anint
:Hope that helps!