Create module-level function using mixin template?

cc uwhglr+ojx6p29qabgu99a6k at grr.la
Wed Apr 30 06:08:23 UTC 2025


On Friday, 25 April 2025 at 16:14:49 UTC, Andy Valencia wrote:
> I have a code pattern, and would like to generate rather than 
> copy/paste.  It _seems_ like mixin templates apply, but I'm not 
> having much luck.  I saw one comment that templates always 
> expand in their own context, so perhaps they're not useful for 
> generating a top-level function?

I assume this is what you wanted to do (given existing functions 
that take a char, create overloads that take a whole string)?
```d
bool bigtest(in string s) {
     return true;
}

bool test1(in char c) {
     return false;
}
bool test2(in char c) {
     return true;
}

bool MyFunc(alias fn)(in string s) {
     if (!bigtest(s)) {
         return false;
     }
     foreach(c; s) {
         if (!fn(c)) {
             return false;
         }
     }
     return true;
}

alias test1 = MyFunc!test1;
alias test2 = MyFunc!test2;

int main() {
     if (!test1("Hello, world")) {
         return(1);
     }
     if (!test2("Hello, world")) {
         return(1);
     }
     return(0);
}
```
Alternatively you could replace the alias lines with something 
like:
```d
static foreach (funcname; ["test1", "test2"]) {
	mixin(format(`alias %s = MyFunc!(%s);`, funcname, funcname));
}
```
Note: `mixin abc;` and `mixin(abc);` do two related but different 
things.
Though personally I would advise against either of these, and 
just call the templated function directly from your code, which 
makes it much more self-documenting about what's going on:
```d
int main() {
     if (!MyFunc!test1("Hello, world")) {
         return(1);
     }
     if (!MyFunc!test2("Hello, world")) {
         return(1);
     }
     return(0);
}
```


More information about the Digitalmars-d-learn mailing list