General reference types

dsimcha dsimcha at yahoo.com
Mon Mar 2 13:23:10 PST 2009


I've been thinking that it would be nice for D to have a general reference
type, which would basically be syntactic sugar for a pointer with no
arithmetic allowed.  This would be safer and more syntactically elegant than
using pointers directly just to get reference semantics for something.  Modulo
a few small rough edges in D's operator overloading, this can be done well in
a library, so core language support is unnecessary.

Such a type might something like:

struct Ref!(T) {
    private T* ptr;

    // Assign val to dereference of ptr.
    void opAssign(U)(ref U val) if(is(U : T));

    // Rebind ptr.
    void opAssign(Ref!(T) val);

    ref T opDot() {
        return *ptr;
    }

    static if(__traits(compiles, (*ptr)++)) {
        void opPostInc() {
            (*ptr)++;
        }
    }

    // Other stuff.
}

I've started prototyping this a little, and filing bug reports/enhancement
requests for a few small hangups I've run into implementing this.  Does this
sound worth doing?  If so, any input on how it should work?



More information about the Digitalmars-d mailing list