www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Re: Little demo of allowing basic types to implement interfaces. Was

reply "Rory McGuire" <rjmcguire gmail.com> writes:
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.
Sep 04 2013
parent "Dicebot" <public dicebot.lv> writes:
It does not exist and often (re)implemented by different people 
here and there.

There still few issues that do not make it vastly more superior 
than existing `isInputRange!T` and friends - I guess this is why 
no one bothered submitting pull requests to the Phobos in the end.

1) You have already stumbled upon this. The fact that templates 
are evaluated at declaration scope + UFCS makes it almost useless 
as generic template. `std.range` imports `std.array` workaround 
this for most common case but this remain unsolved problem in 
general.

2) You can't check for behavior with it, only for signatures (and 
may be subject to any type comparison quirks)

3) It still does not give you the power of Go interfaces / Rust 
traits - one can't use interface parameter type to pass in a 
struct that matches it (via automatically generated fat pointer)
Sep 04 2013