A simplification of the RvalueRef idiom
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Nov 21 12:04:51 PST 2016
First, a reminder that we have this great resource of D idioms:
https://p0nce.github.io/d-idioms/#Rvalue-references:-Understanding-auto-ref-and-then-not-using-it
The link above has an idiom of mixing in a byRef() member function to a
struct. I think I've simplified the template by moving typeof(this)
inside it:
mixin template RvalueRef() // <-- DOES NOT TAKE A PARAMETER ANY MORE
{
alias T = typeof(this);
static assert (is(T == struct));
@nogc @safe
ref const(T) byRef() const pure nothrow return
{
return this;
}
}
struct Vector2f
{
float x, y;
this(float x, float y) pure nothrow
{
this.x = x;
this.y = y;
}
mixin RvalueRef; // <-- SIMPLER USE
}
void foo(ref const Vector2f pos)
{
writefln("(%.2f|%.2f)", pos.x, pos.y);
}
void main()
{
Vector2f v = Vector2f(42, 23);
foo(v); // Works
foo(Vector2f(42, 23).byRef); // Works as well, and use the
same function
}
Let me know if it's not the equivalent of the original.
Ali
More information about the Digitalmars-d-learn
mailing list