Metaprogramming in D : Some Real-world Examples

Lutger lutger.blijdestijn at gmail.com
Thu Nov 12 10:18:32 PST 2009


Bill Baxter wrote:

...
> 
> This is almost just a preprocessor macro trick, except for this line:
>      mixin( FoldStringsOf!visitMethodOf( ["Sum", "Product"] ) );
> 
> The essence is to generate a bunch of methods from a list of names.  I
> was thinking to include a similar example from the world of 3d
> graphics, which is generating all the swizzles of a vector* (got the
> idea from Tom S.).  That's got the method generation from a list, but
> it also generates the list too.

Interesting. I noticed it's also possible to pass a module as an alias and 
to things with it, but haven't come across an example of where that would be 
used. Modules are almost something in D, but just not yet. 

> Another way is to have a swizz member template that lets you do
> v.swiz("zyx").  That's arguably better in that you don't pay for it if
> you don't use it.  But being able to generate all the methods with D
> is still kinda spiffy.
> 
> * Most GPU languages (HLSL,glsl,Cg) have a swizzle syntax, such that
> for a float3 v;   v.zyx  gives you float3(v.z,v.y,v.x).  And this
> works for all suffixes.   v.xxx, v.xzy, etc.  Also for different
> numbers of components.   eg.  v.xz is float2(v.x,v.z).
> 
> --bb

swizzling is a neat example! I also have code that actually implements the 
visitor interface with stubs that print, throw or assert, but it's kind of 
hairy. 



More information about the Digitalmars-d-announce mailing list