Thread overview
Array Template
Dec 15
Vino
Dec 16
Vino
December 15
Hi All,

  Request your help, Is it possible to an template array something similar as below so that we can insert any type of value(string, int etc). If possible can you provide me a example of how to define such array.

Array!(Tuple!(T n))

From,
Vino.B
December 15
On Fri, Dec 15, 2017 at 05:21:55PM +0000, Vino via Digitalmars-d-learn wrote:
> Hi All,
> 
>   Request your help, Is it possible to an template array something
> similar as below so that we can insert any type of value(string, int
> etc). If possible can you provide me a example of how to define such
> array.
[...]

-----
import std.variant;
Variant[] array;
-----

Variant can hold any type, so you can store whatever you want in the array.  To get stuff out, though, you'll need to use .get with the proper type, e.g.:

	Variant[] array;
	array ~= 123;
	array ~= "abc";

	int i = array[0].get!int;
	string s = array[1].get!string;

.get will throw an exception if the boxed type is not compatible with the requested type, e.g.:

	// This will throw an Exception because array[1] doesn't hold an
	// int.
	int i = array[1].get!int;


T

-- 
Gone Chopin. Bach in a minuet.
December 16
On Friday, 15 December 2017 at 17:21:55 UTC, Vino wrote:
> Hi All,
>
>   Request your help, Is it possible to an template array something similar as below so that we can insert any type of value(string, int etc). If possible can you provide me a example of how to define such array.
>
> Array!(Tuple!(T n))
>
> From,
> Vino.B

Do you  mean 'an array of variable types of tuples'.

If so...good luck with that ;-)

December 16
On Saturday, 16 December 2017 at 06:42:53 UTC, codephantom wrote:
> On Friday, 15 December 2017 at 17:21:55 UTC, Vino wrote:
>> Hi All,
>>
>>   Request your help, Is it possible to an template array something similar as below so that we can insert any type of value(string, int etc). If possible can you provide me a example of how to define such array.
>>
>> Array!(Tuple!(T n))
>>
>> From,
>> Vino.B
>
> Do you  mean 'an array of variable types of tuples'.
>
> If so...good luck with that ;-)

Yes, will give a try.

From,
Vino.B
December 18
On Saturday, 16 December 2017 at 14:14:28 UTC, Vino wrote:
>
> Yes, will give a try.
>
> From,
> Vino.B


well, this sort of gets there ;-)

// -----
module test;

import std.stdio;
import std.variant;
import std.typecons;
import std.conv;
import std.string;

void main()
{
    Variant[] arr;

    auto x = tuple(5, "hello", 4.3);
    arr ~= cast(Variant)x;

    auto y = tuple("hello", 4.3);
    arr ~= cast(Variant)y;

    auto z = tuple("hello", "world", 1, 2, 3, 5.5);
    arr ~= cast(Variant)z;

    int i = 0;
    foreach(elem; arr)
    {
        writeln(
                "arr[", i, "] values are : ",
                to!(string)((to!(string)(elem))
                [( indexOf( to!(string)(elem), ")" ) + 2)..($-1)]) );
        i++;
    }

}
// -----