mixin troubles
Jarrett Billingsley
kb3ctd2 at yahoo.com
Tue Oct 3 21:03:17 PDT 2006
"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:
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.
> 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.
> BTW, the docs say that the instantiation syntax for mixins is
>
>
> mixin Foo!() a y;
>
> that is that the template arguments are placed outside and following the
> parenthesis, but that has just got to be wrong.
>
> I quote ...
>
> "
> TemplateMixin:
> mixin TemplateIdentifier ;
> mixin TemplateIdentifier MixinIdentifier ;
> mixin TemplateIdentifier !() TemplateArgumentList ;
> mixin TemplateIdentifier !() TemplateArgumentList MixinIdentifier ;
>
> MixinIdentifier:
> Identifier
> "
I've noticed this in a lot of places in the docs; it showed up when Walter
converted them all over to DDoc format. A lot of the instances have been
fixed. I think he might just have his DDoc macros wrong.
More information about the Digitalmars-d-learn
mailing list