How to 'add' functions to existing type/class/struct/interface...

Matthew Ong ongbp at yahoo.com
Fri May 20 23:11:20 PDT 2011


On 5/19/2011 11:23 PM, Adam D. Ruppe wrote:
>> How to 'add' functions to existing type/class/struct/interface...
>
> You don't. It seems to be that this would break encapsulation anyway.
This block of comments is totally not related to this thread, but just 
to set the record straight.

Not entirely. Only data that you deem safe are expose. Go does not have 
public/private keyword, but they uses first letter of the Identifier of 
Functions or Variables to define encapsulation(strange+implied).

Uppercase first letter = Public.
lowercase first letter = Private.


>> I read from Adam that it is possible and is done within Phobos by D.
>> Could some one provide some sample code to explain that.
>
> Look in std.range for full examples but here's a brief one:
Ok. Thanks.
> void doSomething(T)(T item) if( isMyInterface!T ) {
>       // use item here
> }
> template isMyInterface(T) {
>       static if(is(typeof(
>             // write some code to test the interface here
      ... Do not know what is done here because I am new.
>       )))
>           enum bool isMyInterface = true;
>       else
>           enum bool isMyInterface = false;
> }
Because I am new to D, That is a very strange syntax to me. I suppose 
the std.range example may give more clarity.

>
> You can also use the template straight up, though that's less
> structured:
>
> auto doSomething(T)(T obj) {
>       // write whatever you want here using obj
>       // it won't compile if the obj doesn't match the used functions
> }
This example is more like a static generics in Java for me. But it is a 
form of the polymorphic ability. It does not add

> Or, you can go with a more strictly Go style by using method #1
> and automating the isMyInterface detection. Kenju Hara wrote
> an adaptTo function that does something like this:
>
> interface Interface {
>      void foo();
> }
>
>
> class A { // note it doesn't list the interface here
>       void foo();
> }
>
> void func(Interface i) { }
>
>
> A a = new A();
>
> func(adaptTo!Interface(a));
>
>
> I don't think this has been committed to Phobos yet though.
This last example fits the Go interfaces example the best. I think, but 
there is no code for adaptTo(T). There is no clear idea how this is done.

 From what I can see Go is doing is like in C/C++:
1) using structure to define the data-type. // Class Object is more 
expensive.
2) static functions that bind to that structure datatype. Such static 
functions can be define within the LIB or introduced as new functions 
outside the library.
3) using some form of function pointer to call those static functions.

-- 
Matthew Ong
email: ongbp at yahoo.com



More information about the Digitalmars-d-learn mailing list