Suggestion: function template overloading
Kristian
kjkilpi at gmail.com
Tue Aug 29 10:43:04 PDT 2006
It would be very nice if you could overload function templates as you can
in C++. Here is what I mean:
void f(T)(T val) {...}
void f(int val) {...} //error: conflicts with the template function
It would allow you to write special cases for types that need it.
Here is an example:
int CMP__compare(T)(T left, T right) {
return(left < right ? -1 : (left > right ? 1 : 0));
}
class Array(T) {
typedef int function(T, T) compare_func_t;
final int findOrdered(T obj) {
return(findOrdered(CMP__compare, obj));
}
int findOrdered(compare_func_t cmp_func, T obj) {
//use 'cmp_func' with binary search to find 'obj' from the array...
}
final void sort() {
sort(CMP__compare);
}
void sort(compare_func_t cmp_func) {...};
}
One could ask why not to compare 'obj' directly in 'findOrdered()', i.e.
why to wrap the comparision inside a function template. This way you can
easily affect how 'obj' is searched. For example:
struct Stru {
int a, b;
}
int CMP__compare(Stru left, Stru right) {
if(left.a == -1 || right.a == -1)
return(CMP__compare(left.b, right.b));
else
return(CMP__compare(left.a, right.a));
}
int CMP__compareInv(T)(T left, T right) {
return(-CMP__compare(left, right));
}
void func() {
int pos;
Array!(Stru) a;
Stru s;
...
pos = a.findOrdered(s);
...
a.sort(CMP__compareInv);
}
More information about the Digitalmars-d
mailing list