Template design with required type parameters?

JC johnch_atms at hotmail.com
Fri Nov 10 16:08:00 PST 2006


"Charles D Hixson" <charleshixsn at earthlink.net> wrote in message 
news:ej31kf$1po9$1 at digitaldaemon.com...
> Is it possible to design a template that requires, at compile time, that 
> it's parameters be of a particular type?
>
> I.e., that they include a certain class or interface among their ancestry?
>
> What I'm actually contemplating is a kind of "comparable" interface that I 
> want to require one of the parameters to the Template to have.  I haven't 
> decided whether there should be more than one parameter, partially that 
> depends on just how I should approach this.  (I've also considered just 
> skipping templates altogether and doing the entire thing through normal 
> class inheritance...which would work, but everyone seems to be pushing 
> templates right now.)
>
> It's also true that I may just end up doing "duck typing" if the 
> implementation gets too cumbersome.
>
> I'm not really after ultimate run-time efficiency, I'd prefer clarity 
> combined with "good" efficiency.

You can check template types at compile time.

interface ICanDance {
  void dance();
}

class Dancer : ICanDance {
  void dance() {}
}

void goDancing(T)(T o) {
in {
  static if (!is(T : ICanDance)) // check if T is derived from ICanDance
    static assert(false, "Type must be of type 'ICanDance'.");
}
body {
  o.dance();
}

void main() {
  goDancing(null); // triggers the static assertion
  goDancing(new Dancer); // satisfies the type check
}

Is this what you mean? 





More information about the Digitalmars-d-learn mailing list