Meditation, The Art of Exploitation

Thinking? At last I have discovered it--thought; this alone is inseparable from me. I am, I exist--that is certain. But for how long? For as long as I am thinking. For it could be, that were I totally to cease from thinking, I should totally cease to exist....I am, then, in the strict sense only a thing that thinks.

Friday, February 02, 2007

Introducing libsigc++

libsigc++ library captures the publisher/subscriber pattern nicely in a typesafe modular way. For example,

#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

void run() { sleep(3); signal_detected.emit("Detector news"); }

sigc::signal signal_detected;

void subscriber_fptr(std::string news)
cout << news << ": There are aliens in the carpark!" << endl;

class Subscriber : public sigc::trackable
Subscriber() {} ;
void subscriber(std::string news) { cout << news << ": Aliens alert, aliens alert!" << endl; }
// ...

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";;
cout << "Subscriber stopped subscribing to alienDector news\n";
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