May 17, 2007 Type declaration in interfaces? | ||||
---|---|---|---|---|
| ||||
Say I would want to write a few templated container classes (for example a set, a linked list, a heap, etc. which all implement an interface Container which looks like this: interface Container(T) { void insert(T); void remove(Iterator!(T)); size_t length(); } (Please no comments about the usefullness of the interface and classes itself, they are just examples!) You already see the problem here: Iterator. Well Iterator actually might be defined like this: interface Iterator(T) { T content(); } But the real problem is: Each container class will have its own iterator implementation and remove() should only be defined for exactly that implementation. I could do it like this: class Set(T) : Container(T) { void remove(Iterator!(T) it) { if(cast(SetIterator)it !is null) { // actually do anything } else // runtime fault } } But I'd prefer to do it at compile time somehow. Here an imaginary example which is not syntactically D but should explain what I want: // ------ interface ItBase(T) { T content(); } interface Container(T) { // Means: whatever wants to implement this interface // has to define a type named "Iterator" which in turn // implements ItBase type Iterator(T) : ItBase(T); void insert(T); // Return iterator to some item, this will be the "first" // item on ordered containers Iterator!(T) getIterator(); // Uses the Iterator declared with "type" void remove(Iterator!(T)); size_t length(); } class Set(T) : Container(T) { static class Iterator(T) : ItBase(T) { // TODO: Write a set-specific iterator } // TODO: Implement Container methods plus some more } Container(int) c = new Set(int); c.insert(5); c.insert(6); auto it = c.getIterator(); c.remove(it); Any ideas how to do this? TIA Henning |
Copyright © 1999-2021 by the D Language Foundation