www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Wrap a call?

reply JN <666total wp.pl> writes:
     import std;

     void before()
     {
         writeln("Before");
     }

     void after()
     {
         writeln("After");
     }

     void add(int x, int y)
     {
         writeln(x + y);
     }

     template WrapCall(string call)
     {
         enum WrapCall = "before(); " ~ call ~ "; after();";
     }

     void main()
     {
         mixin WrapCall!"add(1, 2)";
     }

This doesn't work, if I change it to mixin(WrapCall!"add(1, 2")), 
it works, why?
Feb 18
next sibling parent monkyyy <crazymonkyyy gmail.com> writes:
On Wednesday, 18 February 2026 at 19:43:38 UTC, JN wrote:
     import std;

     void before()
     {
         writeln("Before");
     }

     void after()
     {
         writeln("After");
     }

     void add(int x, int y)
     {
         writeln(x + y);
     }

     template WrapCall(string call)
     {
         enum WrapCall = "before(); " ~ call ~ "; after();";
     }

     void main()
     {
         mixin WrapCall!"add(1, 2)";
     }

 This doesn't work, if I change it to mixin(WrapCall!"add(1, 
 2")), it works, why?
what do you mean why, thats a enum use this: ```d void wrapcall(alias F,T...)(T args){ before; F(args); after; } ```
Feb 18
prev sibling next sibling parent Julian Fondren <julian.fondren gmail.com> writes:
On Wednesday, 18 February 2026 at 19:43:38 UTC, JN wrote:
     void main()
     {
         mixin WrapCall!"add(1, 2)";
     }

 This doesn't work, if I change it to mixin(WrapCall!"add(1, 
 2")), it works, why?
This isn't the https://dlang.org/spec/statement.html#mixin-statement , and what your change does it make it that. Contrast: ```d void main() { mixin WrapCall!"add(1, 2)"; mixin(WrapCall); } ```
Feb 18
prev sibling parent Nick Treleaven <nick geany.org> writes:
On Wednesday, 18 February 2026 at 19:43:38 UTC, JN wrote:
     template WrapCall(string call)
     {
         enum WrapCall = "before(); " ~ call ~ "; after();";
     }

     void main()
     {
         mixin WrapCall!"add(1, 2)";
     }
The mixin statement inserts the body of the template into main's scope, so this just declares a string enum: ```d void main() { enum WrapCall = "before(); " ~ "add(1, 2)" ~ "; after();"; } ``` Note that eponymous templates don't do anything special for mixin statements.
 This doesn't work, if I change it to mixin(WrapCall!"add(1, 
 2")), it works, why?
Because that string mixin takes an enum string template instantiation and parses it as if it were code inside main, so you get: ```d void main() { before(); add(1, 2); after(); } ```
Feb 21