Function pickAmong

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 pickAmong(T...)(
  size_t index,
  T values
);

Parameters

NameDescription
index which value to choose, must be less than the number of values
values two or more values to pick from

Returns

A SuperStruct!T wrapping the argument at index.

Example

use pickAmong to form a common return type from different structs

struct Zero  { auto num = 0; }
struct One   { auto num = 1; }
struct Two   { auto num = 2; }

auto val = pickAmong(0, Zero(), One(), Two());
assert(val.num == 0);

val = pickAmong(1, Zero(), One(), Two());
assert(val.num == 1);

val = pickAmong(2, Zero(), One(), Two());
assert(val.num == 2);

Example

pickAmong is similar to std.range.chooseAmong:

import std.range : only, iota, repeat;
import std.algorithm : equal;

auto r = pickAmong(0, only(1), iota(0,3), repeat(1,3));
assert(r.equal([1]));

r = pickAmong(1, only(1), iota(0,3), repeat(1,3));
assert(r.equal([0,1,2]));

r = pickAmong(2, only(1), iota(0,3), repeat(1,3));
assert(r.equal([1,1,1]));

Authors

Ryan Roden-Corrent (rcorre)

Copyright

© 2015, Ryan Roden-Corrent

License

MIT