Ref local variables?
Simen Kjærås
simen.kjaras at gmail.com
Sun Jan 8 13:34:32 PST 2012
On Sun, 08 Jan 2012 18:54:13 +0100, Ben Davis <entheh at cantab.net> wrote:
> Hi,
>
> Is there a reason 'ref' is disallowed for local variables? I want to
> write something like:
>
> MapTile[] map; // It's a struct
>
> ref MapTile tile=map[y*w+x];
> tile.id=something;
> tile.isWall=true;
>
> My actual case is more complicated, so inlining the expression
> everywhere would be messy. I can't use 'with' because I sometimes pass
> 'tile' to a function (which also takes it as a ref). I don't want to
> make it a class since the array is quite big and that would be a lot of
> extra overhead. For now I'm using pointers, but this is forcing me to
> insert & or * operators sometimes, and it also reduces the temptation to
> use 'ref' in the places where it IS allowed, since it's inconsistent.
>
> I hope it's not a stupid question - it's my first one - but I couldn't
> find an answer anywhere. I like most of what I've seen of D so far, and
> I'm very glad to be able to leave C and C++ (mostly) behind!
>
> Thanks,
>
> Ben :)
Quick hack:
struct Ref( T ) {
private:
T* data;
public:
this( ref T value ) {
data = &value;
}
ref inout(T) get( ) inout {
return *data;
}
alias get this;
}
Ref!T byRef( T )( ref T value ) {
return Ref!T( value );
}
unittest {
int a = 3;
Ref!int b = a;
b = 4;
assert( a == 4 );
auto c = byRef( a );
c = 5;
assert( a == 5 );
assert( b == 5 );
}
More information about the Digitalmars-d-learn
mailing list