aGrUM 2.3.2
a C++ library for (probabilistic) graphical models
How to use signaler/listener in aGrUM ?

aGrUM has its own implementation of signalers/listeners.

Let's say that class A has a method f(int i,char ch) and would like to give to everyone the right to know whenever f() is run.

#include <agrum/core/signal/signaler.h>
class A {
public:
gum::Signaler2<int,char> onF; // Note that onF is public and will send an int and a char then
'Signaler2' is used.
void f(int i,char ch) {
//do something
GUM_EMIT2(onF,i,ch); // a signal (with 2 args i and ch) is emitted via the Signaler onF.
}
};
@
#define GUM_EMIT2(signal, arg1, arg2)
Definition signaler2.h:61

Note that for class A, adding signaler is very light : a new public attribute and a GUM_EMITx when needed (where x is the number of args).

Now, how to listen to such a signal ?

#include <agrum/core/signal/Listener.h>
class B : public gum::Listener {
public:
void whenF(const void *src,int i, char ch) { // note the void* src
std::cout<<"object "<<src<<" run f on "<<i<<" and "<<ch<<std::endl;
}
};
// we may have more than one listener
class C : public gum::Listener {
public:
void dummy(void *src,int i,char ch) {
std::cout<<"dummy on "<<i<<" and "<<ch<<std::endl;
}
};
Every class who would catch signal from signaler should derive from Listener.
Definition listener.h:93

Now we have to connect

int main(void) {
A a;
B b1;
B b2;
GUM_CONNECT( a,onF,b1,B::whenF );
GUM_CONNECT( a,onF,b2,B::whenF );
a.f(3,'a');
// b1.whenF and b2.whenF has been executed.
{
C c;
GUM_CONNECT( a,onF,c,C::dummy );
a.f(4,'x');
//c.dummy(), b1.whenF and b2.whenF has been executed.
} // c is destroyed...
a.f(5,'y');
//b1.whenF and b2.whenF has been executed.
}
#define GUM_CONNECT(sender, signal, receiver, target)
Definition listener.h:117