reflection based on my experience so far on compile-time meta-programming in D as a novice user: the problems

Paul Backus snarwin at gmail.com
Mon Sep 14 12:54:49 UTC 2020


On Monday, 14 September 2020 at 12:32:35 UTC, Sebastiaan Koppe 
wrote:
>
> The implied restriction was that the generate function takes a 
> type as its template argument, and then generates a string 
> containing a valid D statement with said type.
>
> But fear not:
>
> ----
>
> string generate(string typeName)() {
>     return "%s bla;".format(typeName);
> }
>
> void bla(T)() {
>     mixin(generate!(T.stringof));
>     bla = 5;
> }

There's no guarantee that `T.stringof` produces a name that's 
valid in the scope where you're mixing it in:

import somelib: Y = X;
alias blaY = bla!Y;
// Error: undefined identifier `X`

In general, it's impossible to round-trip a type through a 
string. The closest thing is .mangleof, which is guaranteed to 
produce a globally-unique result, but can't be converted back 
into a type afterward. So maybe what you actually want is 
`__traits(demangle)`?


More information about the Digitalmars-d mailing list