blazingly fast, lightweight, header only
delegates

Quickstart

$ wget http://bit.ly/simple_delegates -O delegate.h

$ cat <<EOT >> test.cpp

#include "delegate.h"

#include "stdio.h"

struct listener {

    void foo(int x) { printf("got %d\n", x);} };

int main() {

    listener l;

    auto d = dlgt::make_delegate(&listener::foo, l);

    d(42); return 0; }

EOT

$ g++ test.cpp --std=c++11 -o test && ./test

got 42

Features

Some of the advantages of using delegates.

fast

see benchmark section for details

light-weight

minimal memory footprint

easy-to-use

just include one header file and be done – no need to compile anything

Portable

only requires a C++98 compatible compiler - no architecture or hardware dependent code

no dynamic memory allocation

stay in control of your resources – implementation does not use malloc/new

nice syntax

uses template argument deduction so you don’t have to encode the types yourself

Examples

if it’s not easy to use it’s useless

Passing around functions in functional languages like haskell or clojure is how you program in those languages. Passing around functions in C/C++ is possible but more tedious. The syntax for function pointers is quite daunting and relatively limited in it's application. For example it is not possible to pass a member-function around.

delegates take care of some of the problems and allow to easily pass around and store "functions".

                  
class A
{
public:
    int square(int x)
    {
        return x * x;
    }
};
...
auto d = make_delegate(&A::square, a);
...
                  
                

It doesn't matter how many arguments the function has. Template argument deduction takes care of that.

                  
class A
{
public:
    float crazy(int I, char wanna, float go, const char *crazy)
    {
      ...
    }
};
...
auto d = make_delegate(&A::crazy, a);
...
                  
                

Type of delegates

If you wanna know what type the delegate has, just provoke a compiler error. This will tell you the correct type:

                  
int d = make_delegate(&A::crazy, a);
...
tests/delegateTests.cpp:104:13: error:
  no viable conversion from 'delegate<float (A::*)(int, char, float, const char *)>' to 'int'
        int d = make_delegate(&A::crazy, a);
                    ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~
                  
                

Facts

How do delegates perform compared to alternatives?

Linux Benchmark

Performance

Member vs. Static

Performance

Mac Benchmark

Performance

Where to use

pretty much everywhere you develop using C++

embedded

small, constraint systems

desktop

personal computing

cloud

distributed computing

Since we do not rely on any advanced C++ features and make no use of exceptions or dynamic memory management, delegates can be used on all kinds of systems. Ranging from small embedded controllers to full blown server nodes.