Runtime heterogeneous collections?

Steven Schveighoffer schveiguy at gmail.com
Fri Jan 18 13:31:28 UTC 2019


On 1/17/19 11:06 PM, Jonathan M Davis wrote:
> On Thursday, January 17, 2019 1:21:41 AM MST Dukc via Digitalmars-d-learn
> wrote:
>> On Thursday, 17 January 2019 at 02:27:20 UTC, Neia Neutuladh
>>
>> wrote:
>>> 1. Make a wrapper class. Now you can store Object[], or you can
>>> make a
>>> base class or base interface and use that.
>>> 2. Use Variant, which can wrap anything, or the related
>>> Algebraic, which
>>> can wrap a fixed collection of types.
>>
>> 3. Use an union. However, only do this if you always know from
>> outside what type of data is stored in each node. If you need to
>> memoize the type of data for each node, better resort to 1. or 2.
> 
> Variant types are really just user-friendly wrappers around unions. So,
> pedantically, using a variant type such as Variant or Albegbraic and using a
> union are fundamentally the same thing, though obviously, the actual usage
> in terms of the code that you write is not the same, since if you use a
> union directly, you have to deal with the union directly (including figuring
> out how to know which type the union currently holds), whereas with a
> Variant, you're using its API rather than dealing with the union directly.
> In general, it's probably better to use Variant rather than union simply
> because Variant deals with the type safety for you.
> 

A variant is not a union. Algebraic is a union, but Variant can hold ANY 
type, even types your code doesn't know about.

To answer the OP, what he wants is an array of different RedBlackTrees. 
Since RedBlackTree is a class, his code is not far off from something 
that works. This does compile, and produces an Object[]:

     auto arr = [
  redBlackTree(Tuple!(int, "x", int, "y", string, "z")(1, 2, "abc")),
  redBlackTree(Tuple!(int, "x", int, "y", int, "z")(1, 2, 3))
];

Then you have to cast each object into it's appropriate type to use it. 
That is not as easy, as you have to know the exact instantiation of tree 
type.

In this case, you are better off using a union, or an Algebraic as your 
array element type. If you use something like 
https://code.dlang.org/packages/taggedalgebraic it could be quite usable.

-Steve


More information about the Digitalmars-d-learn mailing list