Feature request: interfaces declare types

Henning Hasemann hhasemann at web.de
Wed May 23 12:38:32 PDT 2007


Imagine, you want to write a STL-alike thingy.
You might come to a point, where you want to define an interface that describes
what all your containers (or a special group of them) have in common.
Say:

interface Container(T) {
  T first();
  void remove(T);
}

K, no problem here. But now say you want to extend it to use iterators.
Obviously all your iterators will share an interface. Something like:

interface Iterator(T) {
  T content();
}

No question your iterators will be implemented very differently.
A linked list might put prev and next pointers into it, while
a data structure based on an array might store an elements index.
Lets adapt our Container:

interface Container(T) {
  T first();
  void remove(T);

  Iterator(T) firstIterator();
  void remove(Iterator(T));
}

... but wait! Every implementation of Container(T) will always only accept its
own iterators!
Only way to solve this is to have every remove() method cast the parameter
to its internal used iterator class at runtime, which shouldnt be necessary.

What I request is to be able to write something like:

interface ContainerIterator(T) {
  T content();
}

interface Container(T) {
  type Iterator : ContainerIterator!(T);
  
  T first();
  void remove(T);
  Iterator(T) firstIterator();
  void remove(Iterator(T));
}

In this example the imaginary "type" keyword says:
Whatever class wants to implement this interface has to define a type Iterator
(through a nested class, alias whatever) that in turn is derived from
ContainerIterator!(T).

So in the interface, this type can be used for return and parameter types,
anyone who uses this interface can access the type, too and all neccessary
type-checking could be done at compile time with no additional cost.

Usage example:

// I dont care what container they use
class Foo {
  Container(int) someNumbers;
  // ...
  int popNumber() {
    Container(int).Iterator nr = someNumbers.firstIterator();
    int r = nr.content();
    someNumbers.remove(nr);
    return r;
  }
}

-- 
GPG Public Key: http://keyserver.veridis.com:11371/search?q=0x41911851
Fingerprint: 344F 4072 F038 BB9E B35D  E6AB DDD6 D36D 4191 1851



More information about the Digitalmars-d mailing list