Create module-level function using mixin template?

Ali Çehreli acehreli at yahoo.com
Fri Apr 25 17:35:30 UTC 2025


On 4/25/25 10:24 AM, Andy Valencia wrote:
> On Friday, 25 April 2025 at 16:59:16 UTC, monkyyy wrote:
>> its extremely unclear what your trying to do my best geuss:
> 
> I want to use a mixin template to generate a top-level function. Like, 
> is there a variant of the following which makes a function named "foo1" 
> available?
> 
> Andy
> 
> ```d
> mixin template Foo(alias fn) {
>      int fn() { return 1; }
> }
> 
> mixin Foo!foo1;
> 
> void main() {
>      import std.stdio : writeln;
> 
>      writeln(foo1());
> }
> ```

I think an 'alias' template parameter must refer to an existing symbol, 
which you don't have. Although I've been missing a feature of "string 
parameters without quotes", here is a solution:

mixin template Foo(string fn, int i) {
     int Foo() { return i; }

     mixin ("alias " ~ fn ~ " = Foo;");
}

mixin Foo!("foo1", 1);
mixin Foo!("foo2", 2);

void main() {
     import std.stdio : writeln;

     writeln(foo1());
     writeln(foo2());
}

Ali



More information about the Digitalmars-d-learn mailing list