"static interface" for structs

Marco Leise Marco.Leise at gmx.de
Tue Oct 11 05:30:47 PDT 2011


First things first: I've been told on IRC that this idea has already come  
up and was rejected in favor of template guards. But it wasn't clear what  
the reasons were.

The idea is to have "static interface" or "protocol" for structs similar  
to the "interface" for classes. The benefit comes from the fact that in D  
we often see structs used in a way other languages can't. A prime example  
are function templates for sorting algorithms that can take any kind of  
range (built-in, class, struct). But with this broader use, comes the need  
to be explicit about the interface of a struct akin to interfaces for  
classes. A compiler or IDE can detect missing or incorrectly spelled  
methods on structs that implement a protocol. Readers of your code can  
understand from the declaration that a struct is forward-iterable or  
supports some other protocol.

These are the rules:
1. Protocols share the common symbol space with classes, interfaces, etc.
2. They can be (multiple-)inherited by interfaces and other protocols.
3. They can be implemented by structs as well as classes.

I use "protocol" as a keyword to avoid any confusion with what "interface"  
allows you to do at runtime. Also this is not "C++ concepts" in disguise.  
Actually I didn't know about until now. It is somewhat of a really small  
subset of that though.


protocol InputRange(E) {
	@property bool empty;
	@property E front;
	E popFront();
}

// defines a property that returns the declared range type
protocol ForwardRange(E) : InputRange!E {
	@property typeof(this) save;
}

// just a tag
protocol InfiniteRange(E) : ForwardRange!E {}


I used the range module as an example, just because it is the first that  
came to my head. Actually on browsing the source for a while I realized  
that checks like "hasLength", which look like a candidate for a protocol  
are more flexible than a method/field declaration. length can be a field  
or property and return any integral type. So on 32-bit systems it works  
with 64-bit file sizes and 32-bit indexes on arrays just as well. So even  
if protocols make for a nice syntax, they don't fit the bill. Other ideas  
for struct "interfaces"?


More information about the Digitalmars-d mailing list