Passing Templated Function Arguments Solely by Reference

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 11 10:43:52 PDT 2014


On 07/11/2014 03:38 AM, "Nordlöw" wrote:

 > https://github.com/nordlow/justd/blob/master/random_ex.d
 >
 > is what I have so far. Does this look ok to you?

The following seems redundant because the other isFloatingPoint!E 
version uses the default arguments 0 and 1 anyway.

auto ref randInPlace(E)(ref E x) @trusted if (isFloatingPoint!E)
{
     return x = uniform(cast(E)0,
                        cast(E)1);
}

 > Question: Can I somehow avoid the duplication of logic in
 >
 > - auto ref randInPlace(R)(R x) @safe if (hasAssignableElements!R)
 > - auto ref randInPlace(T)(ref T x) @safe if (isStaticArray!T)

The following works if you pardon the name foo. :p

auto foo(TT)(ref TT x)
{
     foreach (ref e; x)
     {
         e.randInPlace;
     }
     return x;
}

/** Generate Random Contents in $(D x).
  */
auto ref randInPlace(R)(auto ref R x) @safe if (hasAssignableElements!R)
{
     return foo(x);
}

/** Generate Random Contents in $(D x).
  */
auto ref randInPlace(T)(ref T x) @safe if (isStaticArray!T)
{
     return foo(x);
}

Alternatively, a string mixin could be used but they should be reserved 
for when there is no better solution.

Ali



More information about the Digitalmars-d-learn mailing list