Easy way to implement interface properties?

Frustrated c1514843 at drdrb.com
Tue Dec 31 17:33:03 PST 2013


On Wednesday, 1 January 2014 at 01:22:27 UTC, Adam D. Ruppe wrote:
> 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.


But your template mixin is still duplicating generic code that 
should be easily handled automatically. (Generic properties are 
just wrappers around private fields that always have the same 
code (just return or set the field))

I'd like to avoid that. Whether using a template mixin or 
not(which solve the 2nd part of the problem) is there a way to 
generate code for the interface automatically? This would require 
compile time reflection(knowing the names, fields, properties, 
functions, etc...) of the interface then generating the code(as a 
string mixin I guess).



More information about the Digitalmars-d-learn mailing list