Interfaces and Template Specializations

Sergey Gromov snake.scaly at gmail.com
Sun Jan 11 07:52:47 PST 2009


Sun, 11 Jan 2009 07:11:37 -0500, Björn T. Herzig wrote:

> So that would mean that if i would write something that is more
> specialized i would have to negate every specialization for the
> default template?
> 
> void tester(U)(U u) if (is(U : Plugable) && is(U : Printable))
> void tester(U)(U u) if (is(U : Plugable) && !is(U : Printable))
> void tester(U)(U u) if (!is(U : Plugable) && is(U : Printable))
> void tester(U)(U u) if (is(U : int) && !is(U : Plugable) && !is(U :Printable))
> void tester(U)(U u) if (is(U : char) ..........)
> //default template
> void tester(U)(U u) if (!is(U : Plugable) && !is(U : Printable) && !is(U : int) && !is(U : char))
> etc....
> 
> I tried this in a little piece of test code and i need to specialize
> so much with every specialization i add, that the code becomes very
> unpleasant to write (see attachment, it won't compile) 

Maybe you should choose a different design then?  Use compile-time
polymorphism, you seem to do this anyway:

class Test
{
  void print() {...} // printable
}

class Test2
{
  void print() {...} // printable
  void plug() {...} // also pluggable
}

void tester(U)(U u)
{
  static if (!is(typeof(&u.print)))
  {
    static assert(false, "non-printable type");
  }
  else
  {
    static if (is(typeof(&u.plug)))
    {
      u.plug();
    }
    u.print();
  }
}

or maybe use run-time polymorphism--it's hard to tell from this toy case
which would be better for the actual task.



More information about the Digitalmars-d mailing list