Storing a lambda alongside type-erased data
Paul Backus
snarwin at gmail.com
Thu Sep 8 15:02:13 UTC 2022
On Thursday, 8 September 2022 at 03:18:08 UTC, Ali Çehreli wrote:
> I looked at how std.variant.VariantN prints the correct type
> and failed to understand the magic there. :(
>
> Then I came up with storing a lambda that is created when the
> exact type is known. The following simple variant can carry
> arbitrary set of data because the data is provided as sequence
> template parameters (aka variadic).
This is actually pretty much exactly what VariantN does, except
instead of storing a pointer to a lambda, it stores a pointer to
an instance of a template function.
The member variable `fptr` [1] is the equivalent of your
`dataToStr`. It stores a pointer to an instance of the `handler`
template [2]. Whenever a new value is assigned to the VariantN,
`fptr` is updated to point to the template instance corresponding
to the new value's type [3].
[1]
https://github.com/dlang/phobos/blob/v2.100.1/std/variant.d#L217-L218
[2]
https://github.com/dlang/phobos/blob/v2.100.1/std/variant.d#L260-L645
[3]
https://github.com/dlang/phobos/blob/v2.100.1/std/variant.d#L731
More information about the Digitalmars-d-learn
mailing list