What's wrong with std.variant.Variant?

Justin Whear justin.whear at gmail.com
Mon Jun 15 16:04:48 UTC 2020


On Saturday, 13 June 2020 at 19:10:04 UTC, Andrei Alexandrescu 
wrote:
> I was curious about collecting a list of grievances about 
> Variant. It's the oldest piece of generic code in std, and it 
> predates a lot of good language additions.
>
> So what's wrong with Variant? One thing I collected from a 
> coworker is that it doesn't work with Windows DLLs, because in 
> turn typeof() comparison does not work across Windows DLLs.
>
> What are other problems with it?

I don't recall ever having a need for Variant; BUT, I have often 
needed an sum type implementation.  The fact that Algebraic is 
implemented as a specialization of Variant (VariantN technically) 
has made it a non-starter for me.  Specifically, the overhead of 
how the type being stored is checked and retrieved seems super 
heavy-weight compared to a simple tagged union approach.  Last I 
checked (admittedly a while ago), it was not better-C compatible 
and sum types are the more common approach in the kind of code 
that needs to be better-C.

Fortunately, implementing a clean, featureful sum type is really 
easy and fun in D which is probably why there are quite a few 
implementations floating around out there.  That said, the D 
idiom which I generally write in eschews inheritance and classes 
generally and I think is fairly common, so strong standard 
library support would be helpful in preventing unnecessary drift 
and incompatibility; a quick search of code.dlang.com reveals 
these alternatives and I assume that there are many more 
unpublished (I think I have three or four implementations myself):

https://code.dlang.org/packages/sumtype
https://code.dlang.org/packages/tagged_union
https://code.dlang.org/packages/tag
https://code.dlang.org/packages/dadt


More information about the Digitalmars-d mailing list