Returning a reference to be manipulated
Paul Backus
snarwin at gmail.com
Thu Apr 13 17:07:42 UTC 2023
On Thursday, 13 April 2023 at 07:05:10 UTC, Chris Katko wrote:
> Right now, I'm using pointers which resolves to:
>
> ```D
> // float* opIndex(string key){...} using pointer
> (*s["tacos"])++; // works with pointer, but is strange looking
>
> s["tacos"]++; // preferred syntax or something similar
> ```
You can use a wrapper struct with `alias this` to make the
pointer a little nicer to use:
```d
struct Ref(T)
{
T* ptr;
ref inout(T) deref() inout { return *ptr; }
alias deref this;
}
Ref!T byRef(T)(ref T obj)
{
return Ref!T(&obj);
}
struct stats
{
float[string] data;
Ref!float opIndex(string key)
{
return data.require(key, 0).byRef;
}
}
void main()
{
stats foo;
auto x = foo["tacos"];
x++;
assert(foo["tacos"] == 1);
}
```
More information about the Digitalmars-d-learn
mailing list