www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - IDEA: An elegant mechanism for adding an interface to sombody else's

reply Russell Lewis <webmaster villagersonline.com> writes:
I was reading through Walter & Andrei's presentation from the D 
conference and ran across the point that one nice reason for making 
these two syntaxes equivalent
     a.func(b);
     func(a,b);
is that it allows you to add "member functions" to basic types.

This gave me an idea for a way to add an interface to a class that 
didn't declare it originally:
     interface foo {...};
     class bar {...};

     foo foo(bar b)
     {
       // generate a temporary wrapper class which implements the
       // interface and just forwards all calls to b
       return new bar2foo_Wrapper(b);
     }

(I bet that somebody could write a template which would convert any 
class to any interface, provided that the class implemented the correct 
functions!)

Then, anywhere in the code, you could access the "interface" as:
     bar b = new bar;
     foo f = b.foo;

...which, of course, implies that perhaps that should be the (or a) 
standard way to access Interfaces, instead of casts:
     interface fred {...}
     class wilma : fred {...}

     wilma w = new wilma;
     fred  f = w.fred;

Thoughts?
Aug 27 2007
parent Bill Baxter <dnewsgroup billbaxter.com> writes:
Russell Lewis wrote:
 I was reading through Walter & Andrei's presentation from the D 
 conference and ran across the point that one nice reason for making 
 these two syntaxes equivalent
     a.func(b);
     func(a,b);
 is that it allows you to add "member functions" to basic types.
 
 This gave me an idea for a way to add an interface to a class that 
 didn't declare it originally:
     interface foo {...};
     class bar {...};
 
     foo foo(bar b)
     {
       // generate a temporary wrapper class which implements the
       // interface and just forwards all calls to b
       return new bar2foo_Wrapper(b);
     }
 
 (I bet that somebody could write a template which would convert any 
 class to any interface, provided that the class implemented the correct 
 functions!)

Someone could, and I believe someone has, to the extent that current __traits will allow it. See Reiner's post in the thread titled "Proxy objects and controlling/monitoring access". digitalmars.D:57033
 Then, anywhere in the code, you could access the "interface" as:
     bar b = new bar;
     foo f = b.foo;
 
 ...which, of course, implies that perhaps that should be the (or a) 
 standard way to access Interfaces, instead of casts:
     interface fred {...}
     class wilma : fred {...}
 
     wilma w = new wilma;
     fred  f = w.fred;
 
 Thoughts?

I'm in the camp that thinks cast should mean 'watch out I'm doing something potentially dangerous!' And dynamic_casts like that aren't dangerous. So yeh, I'd like to see some syntax besides cast for that. --bb
Aug 27 2007