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
see benchmark section for details
minimal memory footprint
just include one header file and be done – no need to compile anything
only requires a C++98 compatible compiler - no architecture or hardware dependent code
stay in control of your resources – implementation does not use malloc/new
uses template argument deduction so you don’t have to encode the types yourself
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);
...
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);
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
small, constraint systems
personal computing
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.