Template specialization

Bill Baxter dnewsgroup at billbaxter.com
Tue Apr 10 03:51:36 PDT 2007


Derek Parnell wrote:
> I've coded ...
> 
>  template fill_data(T : int)
>  {
>     void fill_data(char[] raw_data, out T t)
>     {
>         t = makeInt( raw_data );
>     }
>  }
> 
>  template fill_data(T : float)
>  {
>     void fill_data(char[] raw_data, out T t)
>     {
>         t = toFloat( raw_data );
>     }
>  }
> 
> and later use it like ...
> 
> 
>   struct Foo
>   {
>       float xFloat;
>       int   xInt;
>   }
>   Foo bar;
> 
>   fill_data(str, bar.xFloat);
>   . . .
>   fill_data(str, bar.xInt);
> 
> but when compiled I get these errors ...
> 
>  test.d(38): template procon2.fill_data(T : int) specialization not allowed
>  for deduced parameter T
>  test.d(46): template procon2.fill_data(T : float) specialization not
>  allowed for deduced parameter T
> 
> What is the point of specialization if the compiler can't tell the
> difference between data types? I expected that the point of using templates
> is to make generic programming simpler.

The way I've understood it is that specialization just doesn't work with 
IFTI.  You have to say:

fill_data!(float)(str, bar.xFloat);
and
fill_data!(int)(str, bar.xInt);

Consequently, I don't use specialization ever.  Use 'static if' checks 
inside the template if you want to have both IFTI and specialization. 
It doesn't look as clean for many cases, but at least it's ugly on the 
library side, rather than the caller side.

-bb


More information about the Digitalmars-d-learn mailing list