Table of Contents
Suppose you already have a function that you want to be called when a signal is emitted, but it takes the wrong argument types. For example, lets try to attach the warn_people(std::string) function to the detected signal from the first example, which didn't supply a location string.
Just trying to connect it with:
myaliendetector.signal_detected.connect(sigc::ptr_fun(warn_people));
results in a compile-time error, because the types don't match. This is good! This is typesafety at work. In the C way of doing things, this would have just died at runtime after trying to print a random bit of memory as the location - ick!
We have to make up a location string, and bind it to the function, so that when signal_detected is emitted with no arguments, something adds it in before warn_people is actually called.
We could write it ourselves - it's not hard:
void warn_people_wrapper() // note this is the signature that 'signal_detected' expects { warn_people("the carpark"); }
but after our first million or so we might start looking for a better way. As it happens, LibSigC++ has one.
sigc::bind(slot, arg);
binds arg as the argument to slot, and returns a new slot of the same return type, but with one fewer arguments.
Now we can write:
myaliendetector.signal_detected.connect(sigc::bind( sigc::ptr_fun(warn_people), "the carpark" ) );
If the input slot has multiple args, the rightmost one is bound.
The return type can also be bound with sigc::bind_return(slot, returnvalue); though this is not so commonly useful.
So if we can attach the new warn_people() to the old detector, can we attach the old warn_people (the one that didn't take an argument) to the new detector?
Of course, we just need to hide the extra argument. This can be done with sigc::hide, eg.
myaliendetector.signal_detected.connect( sigc::hide<std::string>( sigc::ptr_fun(warn_people) ) );
The template arguments are the types to hide (from the right only - you can't hide the first argument of 3, for example, only the last).
sigc::hide_return effectively makes the return type void.