struct and class member alias

Stuart Murray stuart.w.murray at fakey.nospambots.gmail.com
Tue Jun 5 20:14:08 PDT 2007


Jarrett Billingsley Wrote:

> 
> "Stuart Murray" <stuart.w.murray at fakey.nospambots.gmail.com> wrote in 
> message news:f4430d$14oc$1 at digitalmars.com...
> > In the following, the aliases have no apparent effect (although they do 
> > compile). Is there a way to achieve a similar effect? I just want to be 
> > able to access
> > boxInstance.pos.x
> > using
> > boxInstance.x
> 
> It doesn't compile; I get
> 
> foo.d(19): Error: pos.x is used as a type
> foo.d(20): Error: pos.y is used as a type
> foo.d(21): Error: size.x is used as a type
> foo.d(22): Error: size.y is used as a type
> 
> It's no surprise, either.  You're not allowed to make aliases of 
> expressions.
> 
> What you can do is make "properties."  You have a setter and a getter for 
> each property.  Because of some syntactic sugar, you can write "a.x" to mean 
> "a.x()" and "a.x = 5" to mean "a.x(5)".
> 
> Here's the Box class with read/write properties for x and y defined.
> 
> public class Box
> {
>     Coord pos, size;
> 
>     this(in int x, in int y, in int w, in int h)
>     {
>         pos  = new Coord(x, y);
>         size = new Coord(w, h);
>     }
> 
>     public int x()
>     {
>         return pos.x;
>     }
> 
>     public void x(int val)
>     {
>         pos.x = val;
>     }
> 
>     public int y()
>     {
>         return pos.y;
>     }
> 
>     public void y(int val)
>     {
>         pos.y = val;
>     }
> }
> 
> It's a little more verbose than you might like.
> 
> Another solution would be to make public reference fields in Box that refer 
> to the inner pos.x, pos.y etc. members.  But D doesn't have generic 
> reference types, so foo :( 
> 
> 

Interesting that it doesn't compile for you.. It definitely does for me (using DMD v1.014)
This is the example I referred to, if anyones interested:

class A
{
    int foo(int x) { ... }
    int foo(long y) { ... }
}

class B : A
{
    alias A.foo foo;
    override int foo(long x) { ... }
}

Its in the documentation. As I said, it's slightly different thing, but it seems to .. *match*.. 

It is unfortunate to not have reference types a la C++, but I love D in almost every other way :)


More information about the Digitalmars-d-learn mailing list