overloading functions against function templates

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Fri Jul 31 02:33:43 PDT 2009


Walter Bright wrote:
> Currently, that can't be done. But it would be good to get it in for D2. 
> The question is, what rule to use?

Yay! I've been waiting for this! :)


> I suggest that:
> 
> 1. if any functions match, then overload functions the usual way
> 
> 2. if no functions match, then overload the function templates the usual 
> way
> 
> Or reverse the priority of the two.
> 
> What do you think?

I think:

   1: Look for exact function matches
   2: Look for exact function template matches
   3: Look for compatible function matches
   4: Look for compatible function template matches


If you are going to allow ordinary and templated functions to overload 
against each other, there is a problem with IFTI that I think will 
become more visible. It's something I run into all the time:

   T sum(T)(T a, T b) { return a + b; }
   real x = 2.0;
   real y = sum(1.0, x);

The above doesn't compile, because 1.0 is a double literal, while x is a 
real. However, if this was an ordinary function with T->real, it would 
be valid code. I think it should also work with templates.


Granted, I don't know how the matching procedure works now, but for this 
case I picture it could be something like this:

Given:
   T sum(T)(T a, T b, T c) { return a + b + c; }
   sum(x, y, z);

then do the following:

   1: Try T = typeof(x). If it works, use it.
   2: Try T = typeof(y). If it works, use it.
   3: Try T = typeof(z). If it works, use it.
   4: Give template matching error.

-Lars



More information about the Digitalmars-d mailing list