Why we use function template?

like this one:
1
2
3
4
template<class T>
void nice(T a, T b){
cout << a + b<<endl;
}


the template can take int, double, long ...
but i can make it with type cast by just offer a double type function.
1
2
3
void nice(double a, double b){
cout << a + b << endl;
}


and as to specialization like meeting a structure or char type, i can use function overloading instead.

so my question is: why function template?
Last edited on
While it's true that sometimes a set of overloads and a function template are both suitable (e.g. the overload-or-template versions of std::pow and other math functions for integer arguments), sometimes you just can't know all required overloads beforehand.

Consider std::sort: how would you implement it as a set of overloads if you don't know what kind of iterators and comparison functors the users will try calling it with? And if they use a lambda or a std::bind, there simply isn't a mechanism to provide a function overload.
Topic archived. No new replies allowed.