简体   繁体   中英

Why no ambiguity when choosing between templated and non-templated functions with same signatures?

The following code passes asserts:

int foo() { return 1; }

template<typename T>
int foo() { return 2; }

int main() {
  assert( 1 == foo() );
  assert( 2 == foo<int>() );
  return 0;
}

But to my understanding, according to Paragraph 13.3.3/1 of the C++11 Standard:

[...] Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i , ICSi(F1) is not a worse conversion sequence than ICSi(F2) , and then [...] F1 is a non-template function and F2 is a function template specialization [...]

It should not, because signatures end up to be the same. So why is there no ambiguity when foo<int>() is called? What am I missing?

The text you quote is rather dense; you have to read it carefully. "F1 is better than F2 if for all arguments i , ICSi(F1) is not a worse conversion sequence than ICSi(F2)" -- that's true here, since the two conversion sequences are the same, hence, neither is worse than the other. So now you move to the last part: " and then F1 is a non-template function and F2 is a function template specialization". That's true, so F1 is a better match than F2. Substituting foo() and foo<int>() for F1 and F2, respectively, the rule says that foo() is a better match than foo<int>() .

Whoops, I answered the wrong question. As the comment points out, the question is, why does explicitly calling foo<int>() not resolve to foo() ? And the answer is, foo<int>() is a call to an explicit template instantiation, not a call to an overloaded function. Consider:

template <class Ty>
void f(Ty) { }

void f(int);
void g(int);

f(3.14);      // calls f<double> (overloaded function call)
f(1);         // calls f(int) (overloaded function call)
f<int>(3.14); // calls f<int> (explicit call of template instantiation)
g(3.14);      // calls g(int)

In this example, f<int> is the name of a template specialization. It is not the general function named f , so there is no overloading to consider, just like the call to g(3.14) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM