View source code
Display the source code in std/functional.d from which this
page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a
Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Alias std.functional.forward
Forwards function arguments with saving ref-ness.
alias forward(args...)
= fwd;
Example
class C
{
static int foo(int n) { return 1; }
static int foo(ref int n) { return 2; }
}
int bar()(auto ref int x) { return C .foo(forward!x); }
writeln(bar(1)); // 1
int i;
writeln(bar(i)); // 2
Example
void foo(int n, ref string s) { s = null; foreach (i; 0 .. n) s ~= "Hello"; }
// forwards all arguments which are bound to parameter tuple
void bar(Args...)(auto ref Args args) { return foo(forward!args); }
// forwards all arguments with swapping order
void baz(Args...)(auto ref Args args) { return foo(forward!args[$/2..$], forward!args[0..$/2]); }
string s;
bar(1, s);
writeln(s); // "Hello"
baz(s, 2);
writeln(s); // "HelloHello"
Example
struct X {
int i;
this(this)
{
++i;
}
}
struct Y
{
private X x_;
this()(auto ref X x)
{
x_ = forward!x;
}
}
struct Z
{
private const X x_;
this()(auto ref X x)
{
x_ = forward!x;
}
this()(auto const ref X x)
{
x_ = forward!x;
}
}
X x;
const X cx;
auto constX = (){ const X x; return x; };
static assert(__traits(compiles, { Y y = x; }));
static assert(__traits(compiles, { Y y = X(); }));
static assert(!__traits(compiles, { Y y = cx; }));
static assert(!__traits(compiles, { Y y = constX(); }));
static assert(__traits(compiles, { Z z = x; }));
static assert(__traits(compiles, { Z z = X(); }));
static assert(__traits(compiles, { Z z = cx; }));
static assert(__traits(compiles, { Z z = constX(); }));
Y y1 = x;
// ref lvalue, copy
writeln(y1 .x_ .i); // 1
Y y2 = X();
// rvalue, move
writeln(y2 .x_ .i); // 0
Z z1 = x;
// ref lvalue, copy
writeln(z1 .x_ .i); // 1
Z z2 = X();
// rvalue, move
writeln(z2 .x_ .i); // 0
Z z3 = cx;
// ref const lvalue, copy
writeln(z3 .x_ .i); // 1
Z z4 = constX();
// const rvalue, copy
writeln(z4 .x_ .i); // 1
Authors
License
Copyright © 1999-2018 by the D Language Foundation | Page generated by ddox.