View source code
Display the source code in std/variant.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
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.

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.

template visit(Handlers...) ;

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 held types of variant are handled across all handlers. visit allows delegates and static functions to be passed as parameters.

If a function with an untyped parameter is specified, this function is called when the variant contains a type that does not match any other function. This can be used to apply the same function across multiple possible types. Exactly one generic function is allowed.

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.

Contained Functions

NameDescription
visit

Returns

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

Throws

VariantException if variant doesn't hold a value and no parameter-less fallback function is specified.

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)();
writeln(rslt); // -1

// Generic function usage
Algebraic!(int, float, real) number = 2;
writeln(number.visit!(x => x += 1)); // 3

// Generic function for int/float with separate behavior for string
Algebraic!(int, float, string) something = 2;
assert(something.visit!((string s) => s.length, x => x) == 2); // generic
something = "asdf";
assert(something.visit!((string s) => s.length, x => x) == 4); // string

// Generic handler and empty handler
Algebraic!(int, float, real) empty2;
writeln(empty2.visit!(x => x + 1, () => -1)); // -1

Authors

Andrei Alexandrescu

License

Boost License 1.0.