how to use opdot
Ary Borenszweig
ary at esperanto.org.ar
Thu Nov 20 04:53:29 PST 2008
Steven Schveighoffer wrote:
> "Morusaka" wrote
>> Hi,
>>
>> I've read about opdot in D language spec operator overload section, but
>> the little snippet of code provided isn't enough, for me, to figure out
>> what it is supposed to do and how to use it or what it could be usefull
>> for.
>>
>> Could you please help me to get the right way?
>
> opDot is useful if you want to make a 'wrapper' type. That is, you want to
> mimic another type, but you want to slightly alter the behavior. opDot
> allows you to 'inherit' all the member functions and fields from the wrapped
> type. For example, if I wanted to create a wrapper type that added a
> 'blahblah' integer to the type, I could do this:
>
> struct AddBlahBlah(T)
> {
> T _t;
> int blahblah;
>
> T *opDot() { return &_t;}
> }
>
> Now, if I declare an AddBlahBlah!(C) and class C has a member foo():
>
> C c;
> AddBlahBlah!(C) abb = AddBlahBlah!(C)(c);
>
> abb.foo(); // translates to abb.opDot().foo()
> abb.blahblah = 5; // sets abb.blahblah to 5, doesn't affect _t
Wow. That's incredibly useful for doing decorators!
http://en.wikipedia.org/wiki/Decorator_pattern
More information about the Digitalmars-d-learn
mailing list