Create module-level function using mixin template?

Andy Valencia dont at spam.me
Wed Apr 30 18:33:57 UTC 2025


On Wednesday, 30 April 2025 at 06:08:23 UTC, cc wrote:
> 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);
> }
> ```


As a workaround, I had just used a pointer to a function 
argument.  I assumed this--which would make the leaf function 
visible during compilation of the string function--would perform 
better.  But, on 1.40.1 with x86-64, it's about twice as slow!  
But it does show a useful technique which I'm sure I'll use at 
some point.

Thanks,
Andy



More information about the Digitalmars-d-learn mailing list