R-values and const ref

dsimcha dsimcha at yahoo.com
Thu Sep 9 05:56:08 PDT 2010


== Quote from Eldar Insafutdinov (e.insafutdinov at gmail.com)'s article
> A while back dmd stopped allowing rvalues as ref function arguments. I
> entirely understand why it was done, but the same restriction applies to the
> ref const function parameters. This causes a lot of pain and at the moment
> makes me use pass-by-value parameters(most notably when using structs). C++
> doesn't have any problem with const ref and rvalues. Can we please restore
> this behavior for const ref?

FWIW, if you can't use templates and auto ref, there is a (slightly verbose)
solution.  DMD apparently allows overloading ref vs. non-ref, so you can write a
forwarding function to bind to rvalues.  This example compiles and does what it
looks like it should.  Perhaps the spec needs to be clarified so that people know
about this feature and can be sure they're not relying on an obscure
implementation bug.

import std.stdio;

void doStuff(const ref int i) {
    writeln("Doing stuff by ref.");
}

// Note that i needs to be const b/c otherwise when forwarding
// the non-ref version will look like the better match and
// we'll get infinite recursion.
void doStuff(const int i) {
    writeln("Forwarding to ref overload.");
    doStuff(i);
}

void main() {
    doStuff(1);
}


More information about the Digitalmars-d mailing list