Chapter 1. Introduction

Table of Contents

Motivation

Motivation

There are many situations in which it is desirable to decouple code that detects an event, and the code that deals with it. This is especially common in GUI programming, where a toolkit might provide user interface elements such as clickable buttons but, being a generic toolkit, doesn't know how an individual application using that toolkit should handle the user clicking on it.

In C the callbacks are generally handled by the application calling a 'register' function and passing a pointer to a function and a void * argument, eg.

void clicked(void *data);

button * okbutton = create_button("ok");
static char somedata[] = "This is some data I want the clicked() function to have";

register_click_handler(okbutton, clicked, somedata);

When clicked, the toolkit will call clicked() with the data pointer passed to the register_click_handler function.

This works in C, but is not typesafe. There is no compile-time way of ensuring that clicked() isn't expecting a struct of some sort instead of a char *.

As C++ programmers, we want type safety. We also want to be able to use things other than free-standing functions as callbacks.

LibSigC++ provides the concept of a slot, which holds a reference to one of the things that can be used as a callback:

  • free-standing functions as in the example
  • pointers to objects that define operator()
  • pointer-to-member and instance of object to invoke that on (the object must inherit from SigC::Object)

All of which can take different numbers and types of arguments.

To make it easier to construct these, an overloaded template called slot is provided. slot takes an argument (or, where necessary arguments) and returns a generic Slot type that can be invoked with operator().

For the other side of the fence, LibSigC++ provides signals, to which the client can attach slots. When the signal is emitted, all the connected slots are called back.