Self-referencing template parameters
    Erik Rasmussen 
    i_am_erik at yahoo.com
       
    Mon Mar 20 03:03:38 PST 2006
    
    
  
One way that I have found java's generics to be useful is in doing 
something like this:
---
public abstract class Animal<T extends Animal<T>>
{
   public abstract T[] procreate(T mate);
}
public class Monkey extends Animal<Monkey>
{
   public Monkey[] procreate(Monkey mate)
   {
      // make sweet monkey love
   }
}
---
Although you're not strictly forced to by the compiler, if you make it a 
policy to always make your template variable the same as your concrete 
subclass, then you have forced any class that extends Animal to provide 
a way to "procreate" with its own kind.
I seem to be unable to implement this pattern in D.  The following 
doesn't work:
---
abstract class Animal(T : Animal!(T))
{
   abstract T[] procreate(T mate);
}
---
It doesn't like that template definition on the first line.  It says, 
"template instance does not match any template declaration".
Any ideas?
Cheers,
Erik
    
    
More information about the Digitalmars-d-learn
mailing list