Runtime alias?

Andrej Mitrovic andrej.mitrovich at gmail.com
Sat Aug 27 18:40:32 PDT 2011


Currently this won't work:

struct Foo { }
struct Bar
{
    Foo foo;
}

void main()
{
    auto bar = Bar();
    alias bar.foo foo;

    test(foo);
}

void test(Foo) {}

Error: need 'this' to access member foo

alias is used for shortening *type* names. But I think alias could
also be useful as a shorthand for declaring a pointer to a field.
Instead of having to do:

void main()
{
    auto bar = Bar();
    auto foo = bar.foo;
    test(foo);
}

This could easily increment a reference-counted struct behind the
scenes, based on how Foo is defined, so it's not a good solution.

Instead, I would like the alias in my first example to resolve to this:
void main()
{
    auto bar = Bar();

    alias foo.bar foo;
    test(foo)

    // behind the scenes resolves to:
    auto foo = &bar.foo;
    test(*foo);
}

It's not a very important feature, but I kind of miss it when coding
in D. It could simplify my code in certain cases without having to use
with() statements which require indentation and have their fair share
of bugs. It could shorten code that uses multiple fields of various
objects.

Anyway it's just an idea, don't take it too seriously.


More information about the Digitalmars-d mailing list