Create module-level function using mixin template?

Andy Valencia dont at spam.me
Fri Apr 25 16:14:49 UTC 2025


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?

Andy

```d
bool bigtest(in string s) {
     return true;
}

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

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

mixin MyFunc!test1;
mixin MyFunc!test2;

int main() {
     if (!test1("Hello, world")) {
         return(1);
     }
     if (!test2("Hello, world")) {
         return(1);
     }
     return(0);
}
```


More information about the Digitalmars-d-learn mailing list