The most awesome "forward to member" solution?

Laeeth Isharc via Digitalmars-d digitalmars-d at puremagic.com
Sat May 9 16:42:19 PDT 2015


On Sunday, 3 May 2015 at 00:19:37 UTC, Andrei Alexandrescu wrote:
> Hey folks,
>
>
> So in working with the allocator, a common matter has come 
> again to the fore: I need to forward certain functions to a 
> member.

> > So I'm thinking of defining a mixin that would be used like
> this:
>
> struct FreeTree(ParentAllocator)
> {
>     ...
>     mixin(forwardIfDefined("parent",
>         "expand", "reallocate", "allocateAll"));
> }


This was very useful, by the way, with synchronicitous timing.  I 
have various derivative instruments made up of legs.  For example 
an interest rate swap where I pay fixed cash flows on one leg and 
receive floating cash flows on another.  So each swap leg is 
itself an entity (I made them structs), and there are a 
collection of such legs (of differing types) comprising a swap 
(or FRA, FX trade etc).

The parent entity (eg a swap with a fixed leg and a float leg; or 
with two float legs) needs to forward calls to the legs.  Eg if 
you change the notional or maturity of the parent, you probably 
want to change the notionals of the component legs, although in 
special cases they might be different.

I don't want to muck about with Byzantine inheritance systems I 
won't likely myself remember in a year (people seem to underrate 
the value of coherence these days, and fragmentation doesn't 
help).  On the other hand I didn't fancy writing lots of 
boilerplate code just to forward calls to each leg (or to only 
one where it made sense).

So I modified forwardToMember to forwardToLegs (I need to return 
a Swap object, since I want to return the Swap for UFCS and the 
calls to leg methods return the leg itself).

setMaturityDate(DateTime maturity( calls 
fixLeg.setMaturity(maturity) and floatLeg.setMaturity.  And 
setFloatMaturity(DateTime maturity) just calls 
floatLeg.setMaturity(maturity) - ie the call is remapped to a 
different name when forwarding, so the user doesn't need to get 
her hands messy with the nitty gritty of the individual legs.

So now all the glue logic is specified in simple arrays that 
produce the requisite code at compile time.  It's easy to see 
what is going on, maintainable, and the parents are only a very 
spaced-out 100 lines.

So thank you for this, and for all the other nice features in D.


More information about the Digitalmars-d mailing list