How to allow +=, -=, etc operators and keep encapsulation?

Steven Schveighoffer schveiguy at gmail.com
Tue Apr 13 12:52:46 UTC 2021


On 4/12/21 2:16 PM, Jack wrote:
> Give this class:
> 
> ```d
> class A
> {
>      int X() { return x; }
>      int X(int v) { return x = v;}
> 
>      private int x;
> }
> ```
> 
> I'd like to allow use ```+=```, ```-=``` operators on ```X()``` and keep 
> encapsulation. What's a somehow elegant way to do that?

It's really hard to do.

One problem is lifetime management. There is no way to do something like 
`ref`, which does not provide a way to make a copy of the original thing 
(the reference) in @safe code.

But the way I'd tackle it is to write a pseudo-reference wrapper that 
forwards to the getter/setter.

I'm sure there's a mixin template solution that works, I just don't have 
the time to code it out right now.

You can take a look at Mike Franklin's unpublished DIP here for inspiration:
* [DIP conversation](https://github.com/dlang/DIPs/pull/97)
* [DIP 
text](https://github.com/dlang/DIPs/blob/fdd016a16bf1898fda901b9d716f5bcc6021c1a7/DIPs/DIP1xxx-mvf.md)

-Steve


More information about the Digitalmars-d-learn mailing list