1

Is there a practical difference between the following two ways to specialize/overload f? Note the difference in the lines above the specialized/overloaded f.

template <typename T>
T f(T x) {
  return x;
}

template<>
int f(int x) {
  return x + 1;
}

and

template <typename T>
T f(T x) {
  return x;
}

int f(int x) {
  return x + 1;
}
xuhdev
  • 8,018
  • 2
  • 41
  • 69
  • In this case no. related/dupe for the generic question: https://stackoverflow.com/questions/7108033/template-specialization-vs-function-overloading – NathanOliver Nov 18 '19 at 21:56
  • Also note that the second example is an overload, not a specialization. A specialization has to have the `template` keyword in it. – NathanOliver Nov 18 '19 at 21:57
  • @NathanOliver-ReinstateMonica I think there can be some obscure differences. For example, what is `f({42})`? – Brian Bi Nov 18 '19 at 22:01
  • 1
    Even better example: if you specialize, then `f(42)` refers to the specialization. If you overload, then `f(42)` will ignore the overload. – Brian Bi Nov 18 '19 at 22:03
  • 1
    @Brian It depends. In the first code it will fail to compile since no type can be deduced. In the second example it would call the int overload. – NathanOliver Nov 18 '19 at 22:12

0 Answers0