A library similar to boost::bind
Tom S
h3r3tic at remove.mat.uni.torun.pl
Sun Jun 18 14:50:43 PDT 2006
Hey there :)
I've created a template lib similar to boost::bind
(http://www.boost.org/libs/bind/bind.html)
Grab it here:
http://158.75.59.9/~h3/code/bind.rar
Basically, it allows the coder to create 'bound' functions, with some of
their args fixed, but also other fancy stuff.
Examples:
void foo(int a, int b) {}
// create a function out of foo with the second argument fixed to 4
auto b1 = bind(&foo, Arg0, 4);
b1(3); // calls foo(3, 4)
// create a function out of foo with reversed args
auto b2 = bind(&foo, Arg1, Arg0);
b2(1, 2); // calls foo(2, 1)
// create a function out of foo with both args fixed
auto b3 = bind(&foo, 5, 6);
b3(); // calls foo(5, 6)
It can also be used for function compositing, like:
int bar(int a, int b) { return a + b; }
auto b4 = bind(&foo, bind(&bar, Arg0, Arg1), Arg2);
b4(1, 2, 3); // calls foo(bar(1, 2), 3)
auto b5 = bind(&foo, bind(&bar, Arg0, Arg0), Arg0);
b5(1); // calls foo(bar(1, 1), 1)
If a function is declared to take different types that are then bound to
a single param type, automatic type negotiation is done:
void func(int a, float b) {}
auto b6 = bind(&func, Arg0, Arg0);
b6(123); // ok, b6 expects an int
Basically, out of all types for wich Arg[n] is to be used, the one is
found that can be casted to all other
An additional feature of the library is an ability to expand tuples, e.g.
Tuple!(int, float) func2() { return makeTuple(1, 2.2f); }
auto b7 = bind(&func, bind(&func2));
b7(); // calls func(1, 2.2f)
Although func expects two arguments and func2 returns just one, func2
returns a Tuple composed of types that match 'func' so it's
expanded/decomposed to allow such a nesting
The 'bind' function returns an object with an overloaded opCall method.
You can grab a delegate from it by calling .ptr() instead.
More examples can be found in the archive
There's a problem with the library though. It only seems to work on the
windows version of DMD. When compiled on linux, DMD segfaults without
providing any reasonable error message :(
What could also be improved upon, are error messages in case when some
types don't match
Anyway, all constructive feedback is welcome. If you have any feature
suggestions or bug reports, I'd be glad to hear them
--
Tomasz Stachowiak /+ a.k.a. h3r3tic +/
More information about the Digitalmars-d-announce
mailing list