5
template<typename TA, typename TB>
void foo (TA a, TB b); // #1

template<typename T>
void foo (T a, T b); // #2

int a, b;    
foo(a, b);

In this case, foo #2 is called. Why?

timmah2014
  • 175
  • 5
  • 1
    @πάνταῥεῖ: I'm not sure how that relates to this question. – Oliver Charlesworth May 05 '14 at 20:46
  • @OliCharlesworth I wasn't either ;) ... Think dyp's comment matches better what I wanted to express. – πάντα ῥεῖ May 05 '14 at 20:47
  • 8
    In this case, both templates produce a function signature `void foo(int, int)`, so they're selected based on a *partial ordering* aka *which one is more specialized*. – dyp May 05 '14 at 20:47
  • 3
    A *very* detailed explanation can be found here http://stackoverflow.com/q/17005985/420683 – dyp May 05 '14 at 20:51
  • @dyp: Very nice. In fact, 14.5.5.2/2 is exactly the OP's example. – Kerrek SB May 05 '14 at 20:56
  • 1
    @dyp: Thanks. Partial ordering does seem to be the key. I think it's important to note that in partial ordering, a function template can be more _specialized_ than another function template, but that does not imply or require that one is a specialization of the other. The terminology was somewhat confusing me when I was first searching for an answer. – timmah2014 May 05 '14 at 21:46

1 Answers1

1

If you were to make explicit the template parameters, you would use:

foo<int, int>(a, b);

to call the first function.

You would use:

foo<int>(a, b);

to call the second function.

Since you let the compiler choose the function, it chose the more restrictive function, which is the second one.

Why is the second one more restrictive? The compiler has to deduce one type to use the second function. It has to deduce two types to use the first one.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 2
    I think `foo(a, b)` still performs overload resolution, and only uses the second function because that one is more specialized. – dyp May 05 '14 at 21:06
  • IMO the second one is *more* restrictive, ergo *more specialized*: It deduces the type for both arguments individually, and if the deduced types are not the same, deduction fails. – dyp May 05 '14 at 21:07