how to use opdot
Steven Schveighoffer
schveiguy at yahoo.com
Thu Nov 20 04:37:53 PST 2008
"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
The goal of opDot is to allow one to create types that wrap other types that
look almost exactly the same without much effort. For example, the
std.typecons.Rebindable type allows one to create a rebindable const or
invariant class reference while forwarding all member accesses to the
underlying invariant or const instance. This feature is used for extending
the type system without having to extend the language, allowing compiler
enforcement of specific design aspects without defining them in the
compiler.
Normal developers will most likely never need to define opDot.
-Steve
More information about the Digitalmars-d-learn
mailing list