Getting the initial value of a class field in compile time.

Paul Backus snarwin at gmail.com
Sun Feb 9 01:19:55 UTC 2020


On Sunday, 9 February 2020 at 00:57:05 UTC, realhet wrote:
> On Sunday, 9 February 2020 at 00:41:12 UTC, realhet wrote:
>> On Sunday, 9 February 2020 at 00:27:21 UTC, Adam D. Ruppe 
>> wrote:
>
> Using what I've learned:
>
> class A{
>   int i=42;
>
>   void init(){ // reInitialize class fields
>     alias T = typeof(this);
>     mixin([FieldNameTuple!T].map!(n => n~"=(new 
> T)."~n~";").join);
>   }
>
> }
>
> (I also like to live dangerously with string mixins :D)

Tip: don't name a member function `init`, since it will conflict 
with the built-in `.init` property.

Here's a version without string mixins, for comparison:

     void initialize() {
         static foreach (i, field; typeof(this).tupleof) {{
             // force compile-time evaluation
             enum initValue = (new typeof(this)).tupleof[i];
             field = initValue;
         }}
     }


More information about the Digitalmars-d-learn mailing list