Array Template

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Dec 15 17:45:59 UTC 2017


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.


More information about the Digitalmars-d-learn mailing list