Mixin and imports

Paul Backus snarwin at gmail.com
Mon Jun 8 10:28:39 UTC 2020


On Monday, 8 June 2020 at 10:23:24 UTC, jmh530 wrote:
> On Monday, 8 June 2020 at 04:13:08 UTC, Mike Parker wrote:
>> [snip]
>>
>>
>> The problem isn't the mixin. It's the template. Templates take 
>> the scope of their declaration, not their instantiation. So 
>> the mixin is getting the template's scope.
>>
>> Anyway, this appears to work:
>>
>> `double z = foo!"std.math.fabs"(x);`
>
> Thanks, that makes sense.
>
> However, I get the same error with the code below. Am I doing 
> something wrong?
>
> double foo(alias f)(double x) {
>     return f(x);
> }
>
> template foo(string f)
> {
>     mixin("alias foo = .foo!(" ~ f ~ ");");
> }
>
> void main() {
>     static import std.math;
>     double x = 2.0;
>     double y = foo!(std.math.fabs)(x);
>     double z = foo!"std.math.fabs"(x);
> }

If you want to refer to symbols in the scope where the template 
is instantiated, you will have to move the mixin outside of the 
template:

double foo(alias f)(double x) {
     return f(x);
}

template foo(string f)
{
     enum foo = "foo!(" ~ f ~ ")";
}

void main() {
     import std.math: fabs;
     double x = 2.0;
     double y = foo!(fabs)(x);
     double z = mixin(foo!"fabs")(x);
}


More information about the Digitalmars-d-learn mailing list