Generically call a function on Variant's payload?

Nick Sabalausky (Abscissa) SeeWebsiteToContactMe at semitwist.com
Tue Aug 21 21:34:27 UTC 2018


On 08/21/2018 03:27 PM, Steven Schveighoffer wrote:
> 
> If you examine how the code for variant works, it's quite clever. It 
> establishes a "handler" that is generated with full compile-time type 
> info available when the value is *assigned*, but then cast to a function 
> taking a void pointer and an operation. This way, the user of the 
> variant doesn't have to know what is inside, just the handler does. The 
> code that sets the payload is the one that establishes how to use it.
> 
> The same type of pattern could be used to, for instance, provide all the 
> functions that a range uses.
> 
> But it's not something that can be tacked on to Variant. You'd have to 
> write your own type, because you'd have to handle the different 
> functions that you know are common between the types in question (e.g. 
> the operations supported on a variant are here: 
> https://github.com/dlang/phobos/blob/master/std/variant.d#L163)

Oooh, that's really cool! I might try my hand at something like that.

I bet it actually could be generalized to a certain extent. Variant 
would just have to be templated on the expected interface. Then it could 
compile-time loop over the list of functions expected, and introspect 
each of them enough to build the handler and the forwarders. Doesn't 
exactly sound fun to implement, but I'd bet it could be done.


More information about the Digitalmars-d-learn mailing list