pointer to member without 'this' - mem_fun like

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Tue Mar 18 08:02:10 PDT 2008


Vlad wrote:
> Example: writing a map()-like function that works on a collection of 
> objects and calling a method on them, instead of a free function
> 
> Pseudocode:
> (with a 'free function'):
> 
> string in[] = ...
> int out[] = map (in, len);
> 
> (with a 'member_fun'):
> T in[] = ...
> T out[] = map(in, &T.do_something);
> 
> or even:
> T in[] = ...
> int out[] = map(in, &T.get_some_int_property)

Normal D way to do something like this:
---
// Note: 'in' and 'out' are keywords so they can't be used as variables
T[] input = ...
// free function:
int[] out1 = map (input, &len); // if map accepts raw function pointers
                                 // otherwise, use something like below
// member function:
U[] out2 = map(input, (T t) { return t.do_something; });
// or even:
int[] out3 = map(input, (T t) { op1(t); op2(t); return op3(t); });
---
It's a bit longer, but doesn't require extra getters & setters just for 
this.
The second parameter to map in the latter two examples is a delegate 
literal; it can contain any block of code, and can even access local 
variables in the surrounding code if needed.
You'll need to overload map (or turn it into a template function) if you 
want to also accept function pointers as in my first example. Of course 
if you want it to allow multiple input and output array types it'll have 
to be a template function anyway so that shouldn't be a problem.


P.S. Normally the operation to apply is the *first* parameter to a 
function called 'map'.


More information about the Digitalmars-d-learn mailing list