开发者

Heterogeneous container for D

Does D support heterogeneous containers(i.e. an 开发者_StackOverflow中文版array that holds different types)?

I know about tuples but the limitation of not being "return-able" from functions just kills the purpose I have in mind.


I assume you use D2 because I don't know about D1.

In std.typecons there are tuple and Tuple which allow you to use these "non-returnable" aka compile time tuples you mention 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 it's type.

If you really want a list of things you don't know the type at compile time import std.variant and then Variant[] as a list of these things.


Variant[] and variantArray() would do the job, here's 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[]
}


I'll add this for completeness.

I just found out about boxArray(in std.boxer), this might be a solution as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜