Getting the default value of a class member field

kinke noone at nowhere.com
Fri Dec 2 04:14:37 UTC 2022


On Friday, 2 December 2022 at 00:24:44 UTC, WebFreak001 wrote:
> I want to use the static initializers (when used with an UDA) 
> as default values inside my SQL database.
>
> See 
> https://github.com/rorm-orm/dorm/blob/a86c7856e71bbc18cd50a7a6f701c325a4746518/source/dorm/declarative/conversion.d#L959
>
> With my current design it's not really possible to move it out 
> of compile time to runtime because the type description I 
> create there gets serialized and output for use in another 
> program (the migrator). Right now it's simply taking the 
> compile time struct I generate and just dumping it without 
> modification into a JSON serializer.
>
> [...]

Okay, so what's blocking CTFE construction of these models? 
AFAICT, you have a templated base constructor in `Model`, which 
runs an optional `@constructValue!(() => Clock.currTime + 
4.hours)` lambda UDA for all fields of the derived type. Can't 
you replace all of that with a default ctor in the derived type?

```
class MyModel : Model {
     int x = 123;        // statically initialized
     SysTime validUntil; // dynamically initialized in ctor

     this() {
         validUntil = Clock.currTime + 4.hours;
     }
}
```

Such an instance should be CTFE-constructible, and the valid 
instance would feature the expected value for the `validUntil` 
field. If you need to know about such dynamically generated 
fields (as e.g. here in this time-critical example), an option 
would be a `@dynamicallyInitialized` UDA. Then if you 
additionally need to be able to re-run these current 
`@constructValue` lambdas for an already constructed instance, 
you could probably go with creating a fresh new instance and 
copying over the fresh new field values.


More information about the Digitalmars-d-learn mailing list