Hi, I'd like to share an idea I had. It was motivated by the feeling I get when writing template functions and templates altogether. The current template constraint mechanism is awesome cuz it gives power and flexibility. However, I think it could be improved, readibilty wise. Here is my suggestion:

//A new kind of type definition: constraint. Or metatype or whatever. //Can only be used where template type parameters are declared. It CANNOT be used as a type declaration.
constraint InputRange {

  /**
Not really executed, just to implement the constraints. Could also be "invariant" or even a new type of block altogether.
  */
  static this() {
InputRange r; //Can use the "type" directly, or typeof(this).
    auto f = r.front();
    auto isEmpty = r.empty();
    r.popFront();
  }


}

//Can be used directly like an interface, but implies a template underneath.
void myTemplateFunction( InputRange r ) {
  foreach( elt; r ) {
    //Do something clever.
  }
}


Semantically equivalent to:

template __superManglingInputRange(T) {
  static if(
              is(
                  typeof(
                    () {
                      //Put what's in "static this" here.
                      T r;
                      auto f = r.front();
                      auto isEmpty = r.empty();
                      r.popFront();
                    }
                  )
                )
            ) {
    enum __superManglingInputRange(T) = true
  } else {
    enum __superManglingInputRange(T) = false;
  }
}

void myTemplateFunction(T)( T r) if( __superManglingInputRange!T ) {
  //The code.
}

The idea is to eventually be able to do something like this:

constraint InputRange(Elt) {
  Elt front();
  void popFront();
  bool empty();
}

void myTemplateFunction( InputRange!int r ) {
  foreach( elt; r ) { ... }
}

What do you think? Does this feel right to you?

Phil

Reply via email to