Storing a lambda alongside type-erased data

apz28 home at home.com
Fri Sep 9 02:32:28 UTC 2022


On Thursday, 8 September 2022 at 15:02:13 UTC, Paul Backus wrote:
> 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


My implement is similar but a pointer to template struct with 
various functions. The advantage is that you can add various 
attributes to those functions

https://github.com/apz28/dlang/blob/main/source/pham/utl/utl_variant.d#L904
https://github.com/apz28/dlang/blob/main/source/pham/utl/utl_variant.d#L1394



More information about the Digitalmars-d-learn mailing list