generic functions

Chris Nicholson-Sauls ibisbasenji at gmail.com
Fri Apr 27 15:31:00 PDT 2007


Frits van Bommel wrote:
> 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).

Y'know... I didn't even think of that.  Heh.  I told you it was quick.

> 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?

I was just working on the assumption that ints/reals were all he was concerned with.  A 
perfect library-appropriate abs() is another creature.

>> 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...

Ah, oy.  Sometimes I think we should just "implement" cent/ucent as aliases for long/ulong 
in the meantime.  So many things are going to break when they come to fruition as it is.

-- Chris Nicholson-Sauls


More information about the Digitalmars-d-learn mailing list