vibe.d beta banner
get vibe.d
0.10.1

Asynchronous I/O that doesn’t get in your way, written in D

Function algebraic

Converts a given TaggedUnion to a TaggedAlgebraic.

auto algebraic(TU) (
  TU tagged_union
)
if (isInstanceOf!(TaggedUnion, TU));

This allows to access members or operators of a TaggedUnion with a concise syntax.

Example

import taggedalgebraic.visit : visit;

struct Button {
	string caption;
	int callbackID;
}

struct Label {
	string caption;
}

union U {
	Button button;
	Label label;
}

alias Control = TaggedUnion!U;

// define a generic list of controls
Control[] controls = [
	Control(Button("Hello", -1)),
	Control(Label("World"))
];

// just a dummy for the sake of the example
void print(string message) {}

// short syntax using `algebraic`
foreach (c; controls)
	print(algebraic(c).caption);

// slightly longer and noisier alternative using `visit`
foreach (c; controls)
	print(c.visit!(ct => ct.caption));

// low level alternative
foreach (c; controls) {
	final switch (c.kind) {
		case Control.Kind.button:
			print(c.buttonValue.caption);
			break;
		case Control.Kind.label:
			print(c.labelValue.caption);
			break;
	}
}
Authors

Sönke Ludwig

Copyright

Copyright 2015-2019, Sönke Ludwig.

License

www.boost.org/LICENSE_1_0.txt, Boost License 1.0.