Little demo of allowing basic types to implement interfaces. Was in D.annouce
Rory McGuire
rjmcguire at gmail.com
Wed Sep 4 00:02:24 PDT 2013
Just wondering if this exists in the standard library.
I made a function "Implements!(T,I)" that returns true is a given
type "T" implements the interface "I".
http://dpaste.dzfl.pl/d7a727fd
I've found it really helps with keeping some code clean such as
the below:
void main() {
int i = 0x34342343;
writebytes(i);
}
//enum Order { Big };
//interface IRawBytes { ubyte[] bytes(Order); }
interface IRawBytes { ubyte[] bytes(); }
void writebytes(T)(T item) if (Implements!(T, IRawBytes)) {
import std.stdio : writeln;
writeln(item.bytes);
}
ubyte[] bytes(ref int i) {
ubyte* ptr;
ptr = cast(ubyte*)&i;
return ptr[0..i.sizeof];
}
If you decide that IRawBytes.bytes should start taking an Order
parameter you get the same benefits you would have got if you had
used classes with an interface.
More information about the Digitalmars-d-learn
mailing list