Why C++ provides templates ? Same task can be done using function overloading. Is there any advantage of using templates over function overloading?
Asked
Active
Viewed 63 times
0
-
6How you would write `std::swap` with function overloading, for example? – Bathsheba Apr 12 '21 at 08:38
-
3"Same task can be done using function overloading". No it cannot. – n. m. could be an AI Apr 12 '21 at 08:40
-
1how would you write std::vector with function overloading? – user253751 Apr 12 '21 at 08:40
-
2Everything can be done by writing machine code directly, so why do we have programming languages? – molbdnilo Apr 12 '21 at 08:47
1 Answers
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
-
-
1Well 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
-
-
1if 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
-