Multiple Inheritance
Tomas Lindquist Olsen
tomas at famolsen.dk
Fri Sep 28 03:21:51 PDT 2007
Olifant wrote:
> Say you have two interfaces: Visible and Selectable.
>
> You want that everything that inherits from Visible, has the following two
> functions: SetVisible: sets it to visible or not
> GetVisible: returns what you last set it to with SetVisible
>
> You want that everything that inherits from Selectable, has the following
> two functions: SetSelected: sets it to selected or not
> GetSelected: returns what you last set it to with SetSelected
>
> Some classes inherit only from Visible, others only from Selectable,
> others from both.
>
> In C++, you can easily do this: put the implementations in the Visible and
> the Selectable interface.
>
> How can this be done in D? I mean to avoid that everyone who inherits from
> one of them has to write his own implementation of
> GetVisible/SetVisible/GetSelected/SetSelected over and over again, after
> all it's always the same.
>
> Is there some way to get such an effect with a language without multiple
> inheritance, maybe even without inheritance at all, but still with the
> ability to be able to make lists of Visible and of Selectable objects no
> matter what subtype they are?
You could use mixins to provide a default implementation:
interface Visible
{
bool visible();
void visible(bool);
}
interface Selectable
{
bool selected();
void selected(bool);
}
template VisibleImpl
{
private bool _isvisible;
bool visible() { return _isvisible; }
void visible(bool b) { _isvisible = b; }
}
template SelectedImpl
{
private bool _isselected;
bool selected() { return _isselected; }
void selected(bool b) { _isselected = b; }
}
class VisibleAndSelectable : Visible,Selectable
{
mixin VisibleImpl!();
mixin SelectedImpl!();
}
Hope that helps :)
-Tomas
More information about the Digitalmars-d
mailing list