-1
template<typename T> T f(T i) { return i+1; }
int f(int i) { return i-1; }

f(2);

Is this undefined behaviour (note that int f(int) is not a specialization) ? If yes, then please point out where standard carries such case.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Criss
  • 581
  • 5
  • 17

2 Answers2

6

There is no ambiguity here. If there is an invocation of f with an int, the non-template version of the overload will always be chosen as long as both declarations are visible at the point of use.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
5

It is not UB and not even ambiguous, it is just overload resolution:

both are exact match, but one is template function whereas the other is not:

int f(int) is selected.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 1
    In the case where you actually want to do this (have a specific different function `f` for type `int`), what is the difference between template specialization (`template<> int f(int i) { return i-1; }`) and overloading that function (as done int he question)? Is there any advantage on using either of them? Or is it (as I suspect) the exact same thing? – apalomer Aug 13 '18 at 22:35
  • @apalomer: you might ask this question as question instead of as comment. In OP's example, it would be mostly the same but things might be more complicated as partial specialization is not possible with template function. A common example is to handle `T`, `T*` and `int*`. – Jarod42 Aug 13 '18 at 22:54
  • Not necessary to ask it as a question. After digging some bit I found [this](https://stackoverflow.com/questions/7108033/template-specialization-vs-function-overloading) and [this](https://stackoverflow.com/questions/3911031/class-template-specialization-vs-function-overloading) qustions and answers which talk about that topic. Thanks anyway! – apalomer Aug 13 '18 at 23:33