How to get to a class initializer through introspection?

Simen Kjærås simen.kjaras at gmail.com
Tue Aug 4 07:25:37 UTC 2020


On Tuesday, 4 August 2020 at 03:47:44 UTC, Andrei Alexandrescu 
wrote:
> struct S {
>     int a = 42;
>     immutable double b;
>     string c = "hi";
>     char[100] c = void;
>     void func(double);
>     ...
> }
>
> then printDefinition!T would output S during compilation. 
> (Without method bodies, but with all qualifiers and attributes 
> and alignment directives and all.)
>
> From that perspective, clearly there's a need for 
> __traits(initializerString, T, "c") or 
> __traits(initializerString, T, 2). It always returns a string 
> containing the initializer value ("void" for void) so code can 
> either print it or mixin it.
>
> For S, __traits(initializerString, T, 0) returns "42", 
> __traits(initializerString, T, 2) and 
> __traits(initializerString, T, "c") return "\"hi\"", and so on.

The problem with initializerString is it doesn't play nice with 
mixins - when a field is of a type not defined or imported in the 
module that does the mixin, the compiler barfs.

Since the initializer must be a compile-time constant, can't we 
just have the __trait return the value, and void in the case of 
void-initialization? (if so, what do we do for fields not 
explicitly initialized?)

--
   Simen


More information about the Digitalmars-d mailing list