How to 'add' functions to existing type/class/struct/interface...
Adam D. Ruppe
destructionator at gmail.com
Thu May 19 08:23:52 PDT 2011
> How to 'add' functions to existing type/class/struct/interface...
You don't. It seems to be that this would break encapsulation anyway.
> 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:
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
)))
enum bool isMyInterface = true;
else
enum bool isMyInterface = false;
}
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
}
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.
More information about the Digitalmars-d-learn
mailing list