String Interpolation

Arafel er.krali at gmail.com
Mon Oct 23 10:45:45 UTC 2023


On 23/10/23 10:28, Arafel wrote:
> Implementing advanced parsing logic that generates whatever AliasSeq you 
> want based on the input string instead of hardcoding it assuming it's 
> just a variable name shouldn't be conceptually hard, especially not if 
> it already exists, just perhaps tedious.

Just a slightly more advanced version even with introspection and a 
dynamic format string... and even expressions!

Supporting expressions in aliases is a PITA, but it can be done with a 
bit of imagination. A delegate literal returning a voldemort struct 
would probably would work as well:

```d
enum i(string expr) =
     "new class(" ~ expr ~ ") {\n" ~
     "    alias _T = typeof(" ~ expr ~ ");\n" ~
     "    _T _v;\n" ~
     "        this(_T _v) {\n" ~
     "            this._v = _v;\n" ~
     "    }\n" ~
     "    static if (is(_T : int)) {\n" ~
     "        enum formatString =  \"%s (detected integer): %d\";\n" ~
     "    } else static if (is(_T : double)) {\n" ~
     "        enum formatString = \"%s (detected double): %f\";\n" ~
     "    } else {\n" ~
     "        enum formatString = \"%s (default: \" ~ _T.stringof ~ \"): 
%s\";\n" ~
     "    }\n" ~
     "    alias _seq =  imported!\"std.meta\".AliasSeq!(formatString,\"" 
~ expr ~ "\",_v);\n " ~
     "}._seq";

void main() {
     import std.stdio : writefln;
     import std.math : sqrt;

     int a = 5;

     writefln(mixin(i!"a + 10"));
     // a + 10 (detected integer): 15
     writefln(mixin(i!"sqrt(5.0) / 2"));
     // sqrt(5.0) / 2 (detected double): 1.118034
     string b = "5";
     writefln(mixin(i!"b"));
     // b (default: string): 5
}

```

https://run.dlang.io/is/hxxK0f

You can obviously do whatever you need with the input string.


More information about the Digitalmars-d mailing list