Introducing libsigc++
libsigc++ library captures the publisher/subscriber pattern nicely in a typesafe modular way. For example,
Notice how closely the library embraces the publisher/subscriber pattern. It'd been perfect if the functions (connect, disconnect) were renamed to (subscribe, unsubscribe)... C# offers the same pattern with the delegation model (new keywords delegate are introduced in C# to facilitate the pattern).
In order to compile/run the sample code, install libsigc++ and libsigc++-devel packages, the compile command is:
g++ -I/usr/include/sigc++-2.0/ -I/usr/lib/sigc++-2.0/include -o sigcpp_t sigcpp_t.cpp -L/usr/lib -lsigc-2.0
#include < sigc++/sigc++.h>
#include < sigc++/signal.h>
#include < sigc++/signal_base.h>
#include < iostream>
#include < string>
using std::cout;
using std::endl;
class Publisher
{
public:
Publisher(){};
void run() { sleep(3); signal_detected.emit("Detector news"); }
sigc::signalsignal_detected;
};
void subscriber_fptr(std::string news)
{
cout << news << ": There are aliens in the carpark!" << endl;
}
class Subscriber : public sigc::trackable
{
public:
Subscriber() {} ;
void subscriber(std::string news) { cout << news << ": Aliens alert, aliens alert!" << endl; }
private:
// ...
};
int main()
{
Publisher mydetector;
mydetector.signal_detected.connect( sigc::ptr_fun(subscriber_fptr) );
Subscriber sub; // added
sigc::connection sub_plan = mydetector.signal_detected.connect( sigc::mem_fun(sub, &Subscriber::subscriber) ); // changed
cout << "Subscriber subscribed to alienDector news\n";
mydetector.run();
cout << "Subscriber stopped subscribing to alienDector news\n";
sub_plan.disconnect();
mydetector.run();
return 0;
}
Notice how closely the library embraces the publisher/subscriber pattern. It'd been perfect if the functions (connect, disconnect) were renamed to (subscribe, unsubscribe)... C# offers the same pattern with the delegation model (new keywords delegate are introduced in C# to facilitate the pattern).
In order to compile/run the sample code, install libsigc++ and libsigc++-devel packages, the compile command is:
g++ -I/usr/include/sigc++-2.0/ -I/usr/lib/sigc++-2.0/include -o sigcpp_t sigcpp_t.cpp -L/usr/lib -lsigc-2.0
<< Home