Easy way to implement interface properties?
Adam D. Ruppe
destructionator at gmail.com
Tue Dec 31 17:22:26 PST 2013
On Wednesday, 1 January 2014 at 00:52:24 UTC, Frustrated wrote:
> @property int data() { return m_data; } // read property
> @property int data(int value) { return m_data = value; } //
> write property
Put that stuff in a mixin template.
interface A {
@property int data();
@property int data(int value);
}
mixin template A_Impl() {
private int m_data;
@property int data() { return m_data; }
@property int data(int value) { return m_data = value; }
}
class B : A {
mixin A_Impl!();
}
> where implement!A implements all the properties and functions
> in A that are not already defined in B using simple methods
The mixin template handles this too:
class B : A {
mixin A_Impl!();
@property int data() { return m_data; }
@property int data(int value) { return m_data = value; }
}
There, it uses the property from the mixin, but B defines its own
property implementations. Something explicitly written in the
class definition overrides the item with the same name from the
mixin.
Here, this looks silly, but if you had several properties in the
mixin template, you could selectively customize just one while
reusing the others.
Note however that overloads don't cross this. So if class B only
implemented the getter, it would complain that the setter isn't
there: defining one function called "data" meant it didn't bring
in *any* "data" methods from the mixin. But all the others would
still be there.
This interface + impl mixin template is also how I'd recommend
doing multiple inheritance in D, you just do this same deal for
each one.
More information about the Digitalmars-d-learn
mailing list