0

Why C++ provides templates ? Same task can be done using function overloading. Is there any advantage of using templates over function overloading?

Proton
  • 343
  • 4
  • 18

1 Answers1

4

Same task can be done using function overloading

No, it can't

How do you write overloads for types that don't exist yet?

How do you write overloads for types that don't have a name?

How does function overloading help you write multiple similar classes?

And you'd still want templates

Why would you write the same implementation dozens (hundreds, millions?) of times?

Caleth
  • 52,200
  • 2
  • 44
  • 75
  • Is there any other advantage except the one you mentioned – Proton Apr 12 '21 at 08:52
  • 1
    Well there are probably loads more things that function overloading can't do nicely, the first list isn't exhaustive. But the main point is that *not writing code* is by far and away the most important difference – Caleth Apr 12 '21 at 08:58
  • @Proton are they not enough advantages already? – user253751 Apr 12 '21 at 08:58
  • 1
    if you have a class / function that operates on one arithmetic type but needs to handle every option, you will need to copy & paste it to have 10 overloads for every `int`, `float`, `double`, `uint8_t` etc version. now you change some code in their because there was a bug, and you have to apply that change to every overload. I don't think I have to explain why this will slow down debugging and development in general by a lot – Stack Danny Apr 12 '21 at 09:06
  • @StackDanny `std::sort` is more compelling than arithmetic. I don't want to have to correctly transfer state of the art sort implementation to every combination of container and ordering that my programs use, and I don't want to have to send trade secrets to (multiple) compiler vendors for them to do it. – Caleth Apr 12 '21 at 09:14
  • sure, generic implementations become impossible. I think the OP doesn't do any generic stuff, so I wanted to show him how overloading a few types can work temporary, but immediately will land you in a nightmare situation. – Stack Danny Apr 12 '21 at 09:19
  • OP should be *using* existing generic definitions – Caleth Apr 12 '21 at 09:21