Function pick

Wrap one of two values in a SuperStruct that encompasses both types.

This can be used to return a value from one of several different types. Similar to std.range.chooseAmong, but for a broader range of types.

Prototype

auto pick(T1, T2)(
  bool condition,
  T1 a,
  T2 b
);

Parameters

NameDescription
condition which value to choose: a if true, b otherwise
a the "true" value
b the "false" value

Returns

A SuperStruct!(T1,T2) wrapping the selected value.

Example

struct Square { int size; int area() { return size * size; } }
struct Rect   { int w ,h; int area() { return w * h; } }

auto shape(int w, int h) {
  return pick(w == h, Square(w), Rect(w,h));
}

assert(shape(4,5).area == 20);
assert(shape(3,3).area == 9);

Example

pick is useful for something that is a floor wax and_ a dessert topping:

struct FloorWax       { string itIs() { return "a floor wax!";       } }
struct DessertTopping { string itIs() { return "a dessert topping!"; } }

auto shimmer(bool hungry) {
  return pick(hungry, DessertTopping(), FloorWax());
}

assert(shimmer(false).itIs == "a floor wax!");
assert(shimmer(true ).itIs == "a dessert topping!");

Authors

Ryan Roden-Corrent (rcorre)

Copyright

© 2015, Ryan Roden-Corrent

License

MIT