Type-safe C++ Callbacks by iii@binary.net

Based on ideas developed on the following pages:
Callbacks in C++ by Bert Peers [sunsite.dk]
CALLBACKS IN C++ USING TEMPLATE FUNCTORS by Rich Hickey [tutok.sk]

Question: You are writing a class that needs to store a function supplied by the client for later use, what type do you store it as? The first thing that comes to mind is a function pointer (ie void (*funPtr)(void)). This works well if you want the user to be able to supply a global function as a callback, but what happens if they want to supply a method? Sure the same signature will work however this forces the method supplied to be static. There is an easy way to store both types of functions without forcing the method to be static, the answer is functors.

Code Snipet:

 
#include "function1.h"
class A
{
    public:
        int method1( int ) { return 0; }
};

int globalfunction( int x ) { return x; }

A myA;
 
// callback that takes an int and returns an int
Function1<int,int> callback1 = Function::MakeFunction( &globalfunction );
callback1( 5 ); // this calls globalfun( 5 );
 
callback1 = Function::MakeFunction( myA, &A::method1 );
callback1( 5 ); // this calls myA.method1( 5 );

Note that the stored type is independent of any information limiting it to global functions, static methods, or methods of any particular class.

This code has been tested under G++ 2.95.3 and VC++ 6.0.

This code is released under the modified BSD license (also known as the XFree86 license).

Download from the SourceForge Page.

SourceForge Logo