Ambiguity issue with expanding and evaluating single template type parameter enums

Paul Backus snarwin at gmail.com
Tue Dec 28 00:32:03 UTC 2021


On Tuesday, 28 December 2021 at 00:13:13 UTC, data pulverizer 
wrote:
> The types I'm generating are a template type I've constructed 
> for R's SEXP, so that my wrapped numeric vector (struct) type 
> is denoted `RVector!(REALSXP)`. But `alias REALSXP = 
> SEXPTYPE.REALSXP` where `SEXPTYPE` is an `enum`.
>
> So if I start using `T.stringof` where `T = 
> RVector!(SEXPTYPE.REALSXP)` to generate code it starts to 
> create chaos because `T.stringof = "RVector!SEXPTYPE.REALSXP"`, 
> so if I'm trying to convert or instantiate a type using 
> `T.stringof ~ "(x)"`, I'll get `RVector!SEXPTYPE.REALSXP(x)` 
> which gives an error, and various types like this can occur 
> many times in a script. The new template allows me to safely 
> paste the type and get what I want 
> `RVector!(SEXPTYPE.REALSXP)(x)`.

The correct answer here is, "don't use `T.stringof` to generate 
code."

The result of `.stringof` is completely implementation-defined, 
may change arbitrarily between compiler releases, and is not even 
guaranteed to be valid D code in the first place. You should not 
rely on it unless you have literally no other choice.

In this case, the simplest solution is to have your code 
generator accept a string as its input, rather than a type. For 
example:

```d
enum instantiate(string type, string expr) = type ~ "(" ~ expr ~ 
")";
pragma(msg, instantiate!("RVector!(SEXPTYPE.REALSXP)", "x"));
```


More information about the Digitalmars-d-learn mailing list