True value semantics for class or struct?
Ali Çehreli
acehreli at yahoo.com
Thu Nov 29 20:08:48 PST 2012
On 11/29/2012 06:25 PM, js.mdnq wrote:
> Simple values are ones that act atomically and use the standard
> mathematical operations.
>
> Suppose I would like to wrap an int with additional functionality:
>
> struct SmartInt{
> privatedata
> int Value;
> methods
> }
>
> The idea is that SmartInt semantics are treated identical to SmartInt.Value
>
> So SmartInt = 3; is identical to SmartInt.Value = 3;
>
> But since it is a smart int we can do
>
> SmartInt.SomeMethod()
>
> Also, when a the struct is copied I might not want to copy privatedata
> as it might change the functionality(maybe instead of copying I want it
> to be set to 0, through a constructor, or method).
>
> The main purpose though, is to treat SmartInt and SmartInt as one and
> the same semantically. As far as I'm concerned, SmartInt is an int... I
> just "wrapped" it up with some nice functions.
>
> Is anything like this possible in D?
>
>
>
There is 'alias this':
struct SmartInt{
int Value;
double privatedata;
void someMethod()
{}
alias Value this;
/* Note: A more intuitive syntax is coming with dmd 2.061:
*
* alias this = Value;
*
* (I hope I remembered it correctly. :p)
*/
}
void main()
{
auto s = SmartInt(42);
s = 45;
int result = s + 43;
s.someMethod();
}
Ali
More information about the Digitalmars-d
mailing list