On Sunday, 8 March 2015 at 18:38:02 UTC, Dennis Ritchie wrote:
On Sunday, 8 March 2015 at 18:18:15 UTC, Baz wrote:
import std.stdio;
import std.typecons;

alias T = Tuple!(string, int);

void main(string[] args)
{
   T[] tarr;
   tarr ~= T("a",65);
   tarr ~= T("b",66);
   writeln(tarr);
}
----

[Tuple!(string, int)("a", 65), Tuple!(string, int)("b", 66)]

Thanks, will do.

It might be better to use std.variant.Algebraic. An array of tuples is wasteful of memory as you only need one or the other.

import std.variant;

alias IntOrStr = Algebraic!(int, string);

IntOrStr[] makeIntOrStrArray(T...)(T vals)
{
        import std.algorithm;
        import std.array;
        
        auto result = new IntOrStr[](T.length);
        foreach (i, val; vals)
        {
                result[i] = IntOrStr(val);
        }
        
        return result;
}

void main()
{
        IntOrStr[] arr = makeIntOrStrArray(4, "five");
}

Reply via email to