generic functions

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Fri Apr 27 14:27:35 PDT 2007


Chris Nicholson-Sauls wrote:
> Frits van Bommel wrote:
>> orgoton wrote:
>>> [snip] I've seen templates at the D 
>>> documentation, but those require me to instantiate the function. Is 
>>> there anyway to bypass this?
[snip]
>> T abs(T)(T val) { return val >= 0 ? val : -val; }
> 
> On the other hand, template functions with a single parameter like this 
> are practically guaranteed IFTI (implicit function template 
> instantiation) so he needn't explicitly instantiate it.  I think that 
> may be enough for what he seems to be wanting.  So given the function 
> above, 'abs(myvar)' will work just fine.

Good point. I didn't consider it was perhaps _explicit_ instantiation he 
had a problem with, instead of instantiation in general.

> I'm also not sure if there's any way to account for the .min issue 
> without writing the function as a member of a normal template and using 
> a chain of static-if's.
> 
> template abs (T) {
>        static if (is(T == byte )) alias ubyte  R;
>   else static if (is(T == short)) alias ushort R;
>   else static if (is(T == int  )) alias uint   R;
>   else static if (is(T == long )) alias ulong  R;
>   else                            alias T      R;
> 
>   R abs (T val) {
>     static if (is(R : ulong)) const ZERO = 0_UL  ;
>     else                      const ZERO = 0.0_L ;
> 
>     return val >= ZERO ? val : -val;
>   }
> }
> 
> Just a quick something, I make no claims toward perfection.  If he 

Good, because I'm pretty sure that breaks IFTI. You'd have to implement 
the static ifs in a separate template for the cleanest working code (I 
think).

Oh, and it seems to assume only primitive types are used (in the body). 
Any particular reason to use a floating-point zero to compare to? 
Wouldn't a regular int implicitly convert? And also work for 
user-defined types implementing opCmp & opNeg?

> doesn't mind always returning a ulong, I'm sure he could replace all 
> those static-if's with one 'static if(is(T:long))'.

That should work for all currently implemented types. It'll still break 
once cent & ucent are implemented though...


More information about the Digitalmars-d-learn mailing list