How does libsigc++ convert a function into a slot?

518 views Asked by At

I'm working with some basic signal code, and I can't figure out how this function is passed in as an argument. I came across this code in the libsigc++ tutorial:

AlienDetector mydetector;
mydetector.signal_detected.connect( sigc::ptr_fun(warn_people) );

AlienDetector has this member variable:

sigc::signal<void> signal_detected;

And warn_people is a function with a simple print statement:

void warn_people() { printf("They're here!\n"); }

Is there an example in the standard library of using a function like this? How does the compiler understand to "look for" the function that is being passed in?

1

There are 1 answers

0
murrayc On BEST ANSWER

It use a function pointer. Wikipedia has some sample code in C: https://en.wikipedia.org/wiki/Function_pointer#Example_in_C

Function pointers are useful when the actual function to call might not be known until runtime. For instance:

typedef void (*callback_func)(int);
callback_func foo_func;

void set_foo_func(callback_func callback) {
  foo_func = callback;
}

void call_foo_func() {
  foo_func(5);
}

void my_func(int a) {
   ...
}

int main() {
   set_foo_func(my_func);
   call_foo_func();

   return EXIT_SUCCESS;
}

Dereferencing is optional (or meaningless, depending on how you think about it) and I personally prefer it:

void call_foo_func() {
  (*foo_func)(5);
}

set_foo_func(&my_func);

That's just for a static function. It's a little more complicated for member functions. And libsigc++ has lots of very complicated code to do lots of useful things.