Steven Schveighoffer wrote:
"Ary Borenszweig" wrote
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
Not exactly ;) The wrapped type is not equivalent to inheritance.
Ah, right. I forgot the inheritance part. :(
For example, if you have a function that takes a class C, you can't pass an
AddBlahBlah!(C) type into it.
However, a template function which expects a type C or a wrapped C, could
possibly be used as you say.
-Steve