Variant

Alias for VariantN instantiated with the largest size of creal, char[], and void delegate(). This ensures that Variant is large enough to hold all of D's predefined types unboxed, including all numeric types, pointers, delegates, and class references. You may want to use VariantN directly with a different maximum size either for storing larger types unboxed, or for saving memory.

alias Variant = VariantN!(maxSize!(FakeComplexReal, char[], void delegate
()
))

Examples

1 Variant a; // Must assign before use, otherwise exception ensues
2 // Initialize with an integer; make the type int
3 Variant b = 42;
4 assert(b.type == typeid(int));
5 // Peek at the value
6 assert(b.peek!(int) !is null && *b.peek!(int) == 42);
7 // Automatically convert per language rules
8 auto x = b.get!(real);
9 
10 // Assign any other type, including other variants
11 a = b;
12 a = 3.14;
13 assert(a.type == typeid(double));
14 // Implicit conversions work just as with built-in types
15 assert(a < b);
16 // Check for convertibility
17 assert(!a.convertsTo!(int)); // double not convertible to int
18 // Strings and all other arrays are supported
19 a = "now I'm a string";
20 assert(a == "now I'm a string");

can also assign arrays

Variant a = new int[42];
assert(a.length == 42);
a[5] = 7;
assert(a[5] == 7);

Can also assign class values

Variant a;

class Foo {}
auto foo = new Foo;
a = foo;
assert(*a.peek!(Foo) == foo); // and full type information is preserved

Meta

Suggestion Box / Bug Report