mirror hosted by tehsausage.com
PTypes: variant

C++ Portable Types Library (PTypes) Version 2.1


Top: Basic types: variant

The variant class offers a universal and flexible way to store values whose types can not be determined at compile time. A variant object can hold integer, boolean, floating point or string values as well as associative arrays of variants or references to objects derived from component. Variants can change their types at run-time. In return for their flexibility, variants have some memory usage and performance overhead. They always occupy 12 bytes of static or local memory, however, they may also use dynamic memory allocation for strings and arrays.

The variant class provides all possible automatic typecasts, so that in most cases, when variants are used in assignments and function calls, the compiler will generate implicit typecasts appropriate for the context. The typecast functions always try to perform conversion regardless of the current and target types, although it may not always be sensible. For example, if a variant object holds an integer value, an attempt to cast it to a string will result in converting the value to its string representation; if a variant is an associative array, an attempt to cast it to boolean will return true if the array is not empty. Variant typecast routines never generate errors except when a 64-bit integer value is converted to 32-bit int and the value exceeds the allowed range.

A variant variable may itself represent an associative array of variants.

This interface can be useful for (but not limited to) designing interpreters and compilers, working with databases and spreadsheets, etc.

The variant class is declared in <ptypes.h>.

Examples

variant v1 = 11;
variant v2 = "33";
variant v3 = int(v1) + int(v2) + 22;  // explicit typecasts: without them the compiler can't 
variant v4 = string(v2) + " cows";    //    figure out which of + operators to use here
large i1 = v1;                        // implicit typecast is possible here
int a = v2;                           // large-to-int: may generate (evariant*) exception
variant v5;
put(v5, "key1", v1);                  // variants may be associated with both strings and
put(v5, 15, "value2");                //    integer values in variant arrays
variant v6 = v5[15];
variant v7 = v5;                      // a reference to the array is passed

variant varray = aclone(v5);          // array is duplicated

variant item;                         // array iteration example
for (int i = 0; anext(varray, i, item); )
    pout.putf("%d: %d\n", i, int(item));

See also: string, unknown & component, Assignments and typecasts, Arrays, Object references, Utilities


PTypes home