View source code Display the source code in std/variant.d from which this page was generated on github. Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

Template std.variant.visit

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

The delegate or function having the currently held value as parameter is called with variant's current value. Visiting handlers are passed in the template parameter list. It is statically ensured that all types of variant are handled across all handlers. visit allows delegates and static functions to be passed as parameters.

If a function without parameters is specified, this function is called when variant doesn't hold a value. Exactly one parameter-less function is allowed.

Duplicate overloads matching the same type in one of the visitors are disallowed.

Arguments

template visit(Handler...);

Functions

Function name Description
visit

Returns

The return type of visit is deduced from the visiting functions and must be the same across all overloads.

Throws

If no parameter-less, error function is specified: VariantException if variant doesn't hold a value.

Example

Algebraic!(int, string) variant;

variant = 10;
assert(variant.visit!((string s) => cast(int)s.length,
                      (int i)    => i)()
                      == 10);
variant = "string";
assert(variant.visit!((int i) => i,
                      (string s) => cast(int)s.length)()
                      == 6);

// Error function usage
Algebraic!(int, string) emptyVar;
auto rslt = emptyVar.visit!((string s) => cast(int)s.length,
                      (int i)    => i,
                      () => -1)();
assert(rslt == -1);

Authors

Andrei Alexandrescu

License

Boost License 1.0.

Comments