String Interpolation

Imperatorn johan_forsberg_86 at hotmail.com
Mon Oct 23 11:47:35 UTC 2023


On Monday, 23 October 2023 at 10:45:45 UTC, Arafel wrote:
> 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 quick comment. When posting code, be sure to check the 
"Enable Markdown" checkbox to the right of the send button.

If you did, your code would look like this:

```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
}
```


More information about the Digitalmars-d mailing list