Skip to content

Instantly share code, notes, and snippets.

@JakobOvrum
Last active December 14, 2015 06:59
Show Gist options
  • Save JakobOvrum/5047336 to your computer and use it in GitHub Desktop.
Save JakobOvrum/5047336 to your computer and use it in GitHub Desktop.
`values` function, taking a number of values with a common type and returning an aggregate containing the values in order, with a range interface. Useful when a few values need to be returned from a function as part of a range composition.
auto values(Elems...)(auto ref Elems elems) if(is(CommonType!Elems))
{
alias CommonType!Elems ElemType;
static struct StaticArray
{
ElemType[Elems.length] data = void;
size_t i = 0;
bool empty() const
{
return i == data.length;
}
ElemType front() const pure
{
return data[i];
}
void popFront() pure
{
++i;
}
enum length = data.length;
}
StaticArray arr;
foreach(i, ref elem; elems)
arr.data[i] = elem;
return arr;
}
unittest
{
import std.algorithm : joiner;
assert(
values("one", "two", "three")
.joiner(" ")
.array() == "one two three");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment