mixin troubles

Derek Parnell derek at nomail.afraid.org
Tue Oct 3 21:36:33 PDT 2006


On Wed, 4 Oct 2006 00:03:17 -0400, Jarrett Billingsley wrote:

> "Derek Parnell" <derek at nomail.afraid.org> wrote in message 
> news:327lkdzeqky1$.11w3vhc3ana9f.dlg at 40tude.net...
> 
>> Anyhow, what am I doing wrong here ...
>>
>> template Foo(alias b)
>> {
>>    typeof(b) Foo() { return b; }
>> }
>>
>> void main()
>> {
>>    int a = 3;
>>    double b = 3.14;
>>    mixin Foo!(a) y;
>>    mixin Foo!(b) z;
>>    assert(y() == 3);
>>    assert(z() == 3.14);
>> }
>>
> 
> Mixins bug me too.  Here's the "correct" version of your code:

Thanks for patience.
 
>  template Foo(alias b)
>  {
>     typeof(b) Foo() { return b; }
>  }
> 
>  void main()
>  {
>     int a = 3;
>     double b = 3.14;
>     mixin .Foo!(a) y;
>     mixin .Foo!(b) z;
>     assert(y.Foo() == 3);
>     assert(z.Foo() == 3.14);
>  }
> 
> Notice the global scope operators on the mixin instantiations, and the 
> explicit access of y.Foo/z.Foo.
> 
> The reason this happens is that the first mixin Foo!(a) y; mixes in the 
> symbol Foo from inside the template.  Then the second mixin attempts to use 
> the local Foo, which is now a mixed-in function, as a template, which fails. 
> So you have to use the global scope operator to access the actual template 
> declaration.  (Actually the first one is optional.)
> 
> Then, you can't call y(), because although the function Foo is the same name 
> as the mixin Foo, y is of type mixin Foo!(a), and the compiler doesn't 
> interpret y() as a call to Foo.

Ok, I can see the reasoning behind that now and it does make sense in a
strict, pedantic, form ... but OMG that is *such* a horrible mess! I
thought programming languages were supposed to make programming easier. 

>> I was expecting that code to be equivalent to ...
>>
>> void main()
>> {
>>    int a = 3;
>>    double b = 3.14;
>>    typeof(a) y() { return a; }
>>    typeof(b) z() { return b; }
>>    assert(y() == 3);
>>    assert(z() == 3.14);
>> }
> 
> It would be great to be able to generate code like that.

And IMHO a lot more intuitive. In fact my first attempt was this ...

  template Foo(alias a, alias b)
  {
     typeof(b) a() { return b; }
  }
  . . .
  mixin Foo!(y,3);
  assert(y() == 3);

because I thought that the documentation meant 'alias' performs lexical
symbol substitution rather than whatever it does mean, which I still can't
quite interpret.

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
4/10/2006 2:26:53 PM



More information about the Digitalmars-d-learn mailing list