CPP2D icon indicating copy to clipboard operation
CPP2D copied to clipboard

[Missing feature] Possible solution for 'const ref' translation

Open Dgame opened this issue 8 years ago • 1 comments

Hi, great project you have here. I'v read that one of your missing features is the const ref problem: Hard because, unlike in C++, in D we can't pass a rvalue to a const ref parameter That is sadly true and the current built-in solution (auto ref) only works in combination with templates and leads to template bloat, but there is a cheap-trick to solve this issue, maybe it'll help you out:

struct A
{
    private A* self = null;
    public string name = null;

    this(string name)
    {
        this.name = name;
    }

    @nogc
    ref A asRef()
    {
        this.self = &this;

        return *this.self;
    }
}

void test(ref A a1, ref const A a2)
{
    assert(a1.name == "foo");
    assert(a2.name == "bar");
}

void main()
{
    test(A("foo").asRef, A("bar").asRef);
}

Dgame avatar May 29 '16 16:05 Dgame

Thank you Randy, this is an interesting solution. Maybe I could let the user chose between

  • The getRef solution
  • The auto ref solution
  • The pass-by-copy solution (which is the current one)

lhamot avatar May 30 '16 17:05 lhamot