generic functions
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Fri Apr 27 05:28:42 PDT 2007
orgoton wrote:
> I've been trying to create a function that would receive a single variable of any type, like a "abs" function, so that I won't have to code the same function for "real" and "long" var types. What's the most straightforward way to do it? I've seen templates at the D documentation, but those require me to instantiate the function. Is there anyway to bypass this?
No, I don't think there's a good way to bypass this. D is a statically
typed language, so a function needs to know the types of the arguments.
---
// Note: doesn't handle byte.min, short.min, int.min and
// long.min correctly because their positive values don't
// fit into the corresponding type... :(
// (This could be fixed by having abs() return the unsigned
// variant of those types, but I don't feel like typing
// that much)
T abs(T)(T val) { return val >= 0 ? val : -val; }
---
More information about the Digitalmars-d-learn
mailing list