[Issue 8799] Give example of Tuple mapped to a function
via Digitalmars-d-bugs
digitalmars-d-bugs at puremagic.com
Wed Apr 23 03:46:23 PDT 2014
https://issues.dlang.org/show_bug.cgi?id=8799
Andrej Mitrovic <andrej.mitrovich at gmail.com> changed:
What |Removed |Added
----------------------------------------------------------------------------
CC| |andrej.mitrovich at gmail.com
--- Comment #2 from Andrej Mitrovic <andrej.mitrovich at gmail.com> ---
(In reply to Jesse Phillips from comment #1)
> Sorry I miss understood and did not remember that Tuples do auto expand. The
> actual request is mapping the Tuple to a function, as requested on SO:
>
> http://stackoverflow.com/questions/12888263/mapping-variadic-template-
> arguments-in-d
The following is an updated example. However, the problem is this feature isn't
really supported, it just happens to work. There's no telling whether it will
break at some point, so I think we shouldn't document it yet.
-----
/**
Return a Tuple expression of $(D Func) being
applied to every tuple argument.
*/
template Map(alias Func, args...)
{
static auto ref ArgCall(alias Func, alias arg)() { return Func(arg); }
static if (args.length > 1)
alias Map = TypeTuple!(ArgCall!(Func, args[0]), Map!(Func, args[1 ..
$]));
else
alias Map = ArgCall!(Func, args[0]);
}
///
unittest
{
import std.conv;
int square(int arg)
{
return arg * arg;
}
int refSquare(ref int arg)
{
arg *= arg;
return arg;
}
ref int refRetSquare(ref int arg)
{
arg *= arg;
return arg;
}
void test(int a, int b)
{
assert(a == 4, a.text);
assert(b == 16, b.text);
}
void testRef(ref int a, ref int b)
{
assert(a++ == 16, a.text);
assert(b++ == 256, b.text);
}
int a = 2;
int b = 4;
test(Map!(square, a, b));
test(Map!(refSquare, a, b));
assert(a == 4);
assert(b == 16);
testRef(Map!(refRetSquare, a, b));
assert(a == 17);
assert(b == 257);
}
-----
--
More information about the Digitalmars-d-bugs
mailing list