Heterogeneous container for D

Does D support heterogeneous containers (i.e. an array that contains different types)?

I know about tuples, but the limitation of not returning to functions just kills the target I mean.

+7
source share
3 answers

I assume you are using D2 because I do not know about D1.

There are tuple and tuple in std.typecons that allow you to use these "irrevocable" or "compilation time tuples" to create runtime values.

 import std.typecons, std.stdio; Tuple!(int, string, int[]) f() { return tuple(5, "xyz", [3, 4, 5]); } void main() { auto x = f(); writefln("%s is %s", x[1], x[0]); //indices have to be copile-time constants } 

Use tuple(v1, v2) as the value and Tuple!(T1, T2) as you type it.

If you really need a list of things that you donโ€™t know the type during the import compilation of std.variant , then Variant[] as a list of these things.

+7
source

Variant [] and variantArray () will do the job, here are some examples

 module test; import std.variant, std.stdio; Variant[] f() { return variantArray(5, "xyz", [3, 4, 5]); } void main() { auto x = f(); writeln(x); // [5, xyz, [3, 4, 5]] writefln("%s is %s", x[1], x[0]); // xyz is 5 x ~= Variant(890); string s = "abc"; x ~= Variant(s); class C {}; x ~= Variant(new C()); x ~= Variant(new int[2]); x[$-1][0] = 5; foreach (e; x) { write(e, " "); // 5 xyz [3, 4, 5] 890 abc test.main.C [5, 0] } f2(x); Variant[] a = variantArray("23", 23); Variant[] b = new Variant[3]; Variant[] c = [Variant(12), Variant("a")]; } void f2(Variant[] va) { writeln(typeid(va)); // std.variant.VariantN!(maxSize).VariantN[] } 
+5
source

I will add this for completeness.

I just found out about boxArray (in std.boxer), it could be a solution too.

0
source

All Articles