Another interesting hack: expand a static array into parameter arguments

Artur Skawina art.08.09 at gmail.com
Thu Apr 3 06:05:41 PDT 2014


On 04/03/14 10:56, Andrej Mitrovic wrote:
> On 4/2/14, Artur Skawina <art.08.09 at gmail.com> wrote:
>>    template expand(alias A, alias M=Delay) {
>>       mixin(q{alias expand = TypeTuple!(}
>>              ~ iota(A.length).map!q{",M!(A,"[!a..$]~text(a)~")"}().join()
>>              ~ q{);});
>>    }
> 
> You can always use string mixins for these hacks. But they are
> terrible to debug, and likely slower to compile.

Actually, they are *much easier* to debug than the recursive templates
-- because you can always look at the generated code, something that
is impossible when using the templates.

> I can barely make out
> what the above code does even though I deal with mixins and templates
> every day.

Demonstrating exactly this was of course the point of my post. What's
hard to read is not the mixin part, that's just one mixin with one
trivial declaration. It's the iota based chain that obfuscates what's
going on. This kind of code gets proposed here all the time, and the
effect is that people new to D see these examples, get a completely
wrong impression of the language, run away screaming and never look back.

In this case there is no really good alternative as the recursive-
templates are unreadable and bug-prone, a foreach-based solution
would be a bit too verbose, and D doesn't have a static-foreach.
Looking at the above code now, I realize that some of the obfuscation
wasn't required; it was caused by my ignorance of D's std lib (which
i never use, except for meta-programming). So, a saner version could
look like:

   template expand(alias A, alias C="A[I]") {
      auto ref M(alias I)() @property { return mixin(C); }
      mixin(q{alias expand = TypeTuple!(}
             ~ iota(A.length).map!q{"M!"~text(a)}().join(",")
             ~ q{);});
   }
   
That is actually not so bad; I was initially hoping for this
approach to turn out much, much worse... :^)
I guess, I'll need to look for another example of functional-style-gone-bad...

artur


More information about the Digitalmars-d mailing list