Getting the default value of a class member field
WebFreak001
d.forum at webfreak.org
Fri Dec 2 00:24:44 UTC 2022
On Thursday, 1 December 2022 at 23:02:31 UTC, kinke wrote:
> On Thursday, 1 December 2022 at 08:09:05 UTC, WebFreak001 wrote:
> [...]
>
> AFAIK, there is no way. Unlike a struct's init symbol, a class'
> one doesn't necessarily represent a valid instance state - it's
> just the raw payload before invoking a ctor (which constructs a
> valid instance), and the state 'dead' memory is reset to after
> finalizing an object instance (to prevent dead pointers keeping
> other GC refs alive).
>
> If the ctor worked at CTFE, one could use:
> ```d
> int get() {
> scope x = new X;
> return x.x;
> }
> enum bla = get();
> ```
> to get the `x` value of a *valid* instance, which might be
> different than the static initializer (if modified in the ctor).
>
> I guess the main question is why do you require the static
> initializers of these fields at compile-time.
> `__traits(initSymbol)` was added to aid in manual blitting at
> runtime.
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.
I might be abusing classes a little bit here, but they provide
the easiest way to do a variety of things:
- `is(T : Model)` and especially type specialization like `void
foo(T : Model)(T x)` is much easier to write and use
- it basically allows me to inject methods into my type (using
template parameter `this This` I can even get my real type)
- it's the most easy and pretty to type for the user. A struct
with `mixin Model` would be quite verbose imo and doesn't allow
Model to define custom fields easily, because they would break
the implicitly generated constructor
More information about the Digitalmars-d-learn
mailing list