Eponymous/anonymous mixin templates

Jeffrey Tsang via Digitalmars-d digitalmars-d at puremagic.com
Sun Jun 7 02:05:27 PDT 2015


I've been doing some fun template metaprogramming recently for a 
few projects, and I have to say the expressive power of mixin 
templates is quite staggering. I've noticed a strongly recurring 
pattern in my usage (mostly trying to get compile-time templated 
code generation, "parser from template args for input spec" for 
example):

A lot of the time, I use a mixin template to define exactly one 
symbol, and at instantiation I wish to use that symbol 
immediately, once.

This has a strong connection with both the eponymous template 
trick and anonymous expressions, and essentially is a combination 
of both - a templated anon expression looked up at instantiation 
site.

Currently, the standard workaround is defining a dummy name 
within the mixin template to do the work. The point of the 
eponymous trick is of course, to avoid this namespace pollution, 
or at least brainspace pollution.

The easiest solution I can think of is to create a second type of 
MixinExpression:

"mixin" "(" MixinTemplateName TemplateArguments_opt ")"

which extends the existing string mixin syntax. This expression 
gets rewritten into the symbol declared as the MixinTemplateName, 
along the lines of the eponymous trick alias, which is 
instantiated as a mixin. The mixin template contents are 
otherwise not imported into scope.

The only hypothetical ambiguity is if the mixin template itself 
resolves to a string literal, whether the result is to be 
compiled or not. However, it requires explicitly naming a mixin 
template, which is categorically different from a string, and to 
me it's completely safe to treat the result of the expression as 
a literal string symbol.

With this, an extended request/alternate solution would be to 
allow writing eponymous mixin templates as well, in the same way 
normal eponymous templates are.

What this looks to me is effectively making "mixin" a modifier 
keyword on templates in general, to bind at instantiation site 
rather than declaration site, and following all the logical 
consequences. Current TemplateMixins naturally become general 
instantiation imports, like using a normal template in a noop.


More information about the Digitalmars-d mailing list