Eponymous/anonymous mixin templates

Artur Skawina via Digitalmars-d digitalmars-d at puremagic.com
Tue Jun 9 04:30:47 PDT 2015


On 06/08/15 22:03, Jeffrey Tsang via Digitalmars-d wrote:
> Recursive mixin templates, which is mostly the reason I'm using this, won't work:
> 
> string foo(string x)() {
>     return x;
> }
> 
> string foo(string x, T...)() {
>     mixin foo!T _foo;
>     return x ~ y ~ _foo.foo();
> }
> 
> // mixin foo!("a", "b"); // dies on foo not a template

No, it's just another D "feature" that gets in the way -
the name of a template resolves to the current instantiation
when used inside the template. If your templates are in module
scope the workaround is simple:

   string foo(string x, T...)() {
       mixin .foo!T _foo;
       return x ~  _foo.foo();
   }

It they are not, it gets more interesting.


>>> 3. Inline/anonymous mixins
>>>
>>> Some way of writing the equivalent of
>>>
>>> bar = (mixin foo!T)() + 3;
>>
>> This part I'm not sure about. Can't think of an interesting
>> use case, that wouldn't be better handled in some other way.
>> The obvious workaround would be:
>>
>>    bar = { mixin foo!T f; return f()+3; }(); // today: `f.foo()+3`
>>
>> [`{...}()` might result in a lambda/closure right now, but that
>>  should really be fixed (ie defined as a special case)]

> Yeah, it's probably easier to do
> 
> auto foo = { mixin foo!T f; return f.foo; }()
> 
> and take one name. With the mixin using enclosing scope, can it be function and not delegate?

No, but a delegate that's immediately executed could be placed
inline and does not require a closure. Some way to use statements
and declarations inside expressions is needed anyway, and this
syntax would be natural in D (even C compilers have this as an
extension, eg gcc's "statement expressions").

> I meant
>     auto foo = { mixin foo!T f; return &f.foo; }();
> and then use the function normally.

That may work for function, which have effectively infinite
lifetime, but is not a good idea for other objects.

artur


More information about the Digitalmars-d mailing list