Open source dmd on Reddit!

Daniel Keep daniel.keep.lists at gmail.com
Sat Mar 7 21:08:41 PST 2009



Walter Bright wrote:
> Daniel Keep wrote:
>> I use mixins with CTFE functions WAY MORE than I use them with templates.
> 
> I'm not surprised. I feel the template mixins were probably a mistake.

Well, there's really a few things at play here:

1. I use templates for simple forward code generation based on types.  I
use CTFE for complex code generation that requires parsing or any
customisability more involved than specifying what T is.

2. Because of most of this, most of my templates are self-contained
while my CTFE is meant to be mixed in to another context.

3. String mixins let me insert functionality and execute it in a single
line.  If I use a templated function, it doesn't have access to its
context.  If I mix it in first, then I have to have a second line to
invoke it.  That is, this:

> mixin(doStuff);

versus

> mixin doStuff;
> _doStuff();

4. An added issue is that there is *no way* to replicate this with
templates:

> mixin(`
>   private int _storage_foo;
>   public int foo() { return _storage_foo; }
>   public int foo(int v) { return _storage_foo = v; }
> `);

This is generally an issue where I have a mixin that implements some
interface, but needs backend "wiring" exposed in places to the mixin-ing
context.

Ideally, I'd be able to do this:

> mixin Foo;
>
> template Foo
> {
>     private int _counter_foo;
>     mixin private int _storage_foo;
>     public int foo() { ++_counter_foo; return _storage_foo; }
>     public int foo(int v) { ++_counter_foo; return _storage_foo = v; }
> }

This way, I can specify that the protection attributes are referring to
the mixin-ing context, and not to the template itself.

I think the major issue is that string mixins represent a superset of
template mixin functionality.  I wouldn't say they were a mistake: more
that they haven't kept pace.

At the end of the day, string mixins are indispensable as a "safe" form
of text substitution... but they are a still a hack that should, in most
cases, be replaced with better language facilities.

  -- Daniel


More information about the Digitalmars-d-announce mailing list