Type unions in D

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Sep 17 07:56:41 PDT 2009


Daniel Keep wrote:
> 
> language_fan wrote:
>> Wed, 16 Sep 2009 12:41:06 +0200, Fawzi Mohamed thusly wrote:
>>
>>> On 2009-09-16 02:40:02 +0200, Justin Johansson
>>> <procode at adam-dott-com.au> said:
>>>> A colleague of mine is suggesting that I really do take a closer look
>>>> at D2 now but I'm not sure that I'm ready to go standing on the
>>>> bleading bleading (the blood doesn't clot) edge just right yet. :-(
>>>>
>>>> JJ
>>> Tango has variant (tango.core.Variant), and is D1, if that could be an
>>> option for you.
> 
> Tango and Phobos2's Variants are very different beasts.
> 
> Phobos2's Variant is a discriminated union; you give it a set of types,
> and that's what it can store.  The general-purpose one, I believe, can
> store any type so long as it's no larger than the biggest primitive
> types (it can't store big structs or static arrays, for example).

std.variant includes three parameterized types. One is the backend 
VariantN, which has the maximum size as a template argument, so it can 
accommodate any type size as long as the maximum is known in advance. 
The second is Algebraic, which is useful when you want to model a holder 
for any of a finite and known set of types. Essentially Algebraic 
aliases itself to VariantN with an appropriately computed maximum size.

Finally, there is the generic Variant which can hold any type in an 
unbounded set. Until last dmd release, Variant had the limitation that 
types larger than a delegate could not be stored directly. I fixed that, 
so now for large types Variant uses dynamic allocation and pointers 
under the wraps.

I have big plans with Variant - I want to make it (or a related type) 
the variable type common in dynamic languages, with flexibility, dynamic 
invocation using common syntax, the works. So if you write a short 
script and want dynamic typing, you should be able to use Variant 
throughout.


Andrei



More information about the Digitalmars-d mailing list