std.variant

This module implements a discriminated union type (a.k.a. tagged union, algebraic type). Such types are useful for type-uniform binary interfaces, interfacing with scripting languages, and comfortable exploratory programming.

A Variant object can hold a value of any type, with very few restrictions (such as shared types and noncopyable types). Setting the value is as immediate as assigning to the Variant object. To read back the value of the appropriate type T, use the get method. To query whether a Variant currently holds a value of type T, use peek. To fetch the exact type currently held, call type, which returns the TypeInfo of the current value.

In addition to Variant, this module also defines the Algebraic type constructor. Unlike Variant, Algebraic only allows a finite set of types, which are specified in the instantiation (e.g. Algebraic!(int, string) may only hold an int or a string).

Warning: Algebraic is outdated and not recommended for use in new code. Instead, use std.sumtype.SumType.

Members

Aliases

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

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.

Classes

VariantException
class VariantException

Thrown in three cases:

Functions

variantArray
Variant[] variantArray(T args)

Returns an array of variants constructed from args.

Structs

VariantN
struct VariantN(size_t maxDataSize, AllowedTypesParam...)

Back-end type seldom used directly by user code. Two commonly-used types using VariantN are:

Templates

Algebraic
template Algebraic(T...)

Algebraic data type restricted to a closed set of possible types. It's an alias for VariantN with an appropriately-constructed maximum size. Algebraic is useful when it is desirable to restrict what a discriminated type could hold to the end of defining simpler and more efficient manipulation.

maxSize
template maxSize(Ts...)

Gives the sizeof the largest type given.

tryVisit
template tryVisit(Handlers...)

Behaves as visit but doesn't enforce that all types are handled by the visiting functions.

visit
template visit(Handlers...)

Applies a delegate or function to the given Algebraic depending on the held type, ensuring that all types are handled by the visiting functions.

Meta

Credits

Reviewed by Brad Roberts. Daniel Keep provided a detailed code review prompting the following improvements: (1) better support for arrays; (2) support for associative arrays; (3) friendlier behavior towards the garbage collector.