If we can specialize code using function overloading.why the need of Template specialization
Because are different things with different behaviors.
A practical example.
The following example compile and link without problem
#include <string>
void foo (std::string const &)
{ }
int main ()
{
foo("abc");
}
Observe that "abc" can be converted to a std::string but isn't a std::string (is a char const [4]).
So, calling a regular (non-template) function, the arguments are converted, when necessary.
Observe the following code
#include <string>
template <typename T>
void foo (T const &);
template <>
void foo (std::string const &)
{ }
int main ()
{
foo("abc");
}
Now the code compile but doesn't link: foo() is a template (only declared) template function with only the std::string full specialization defined.
This time, the compiler deduce the type of the argument (char const [4], different from std::string) so gives a liner error because the general version of foo() isn't defined.
This way you can impose that foo() can be called only with a std::string, not with a value convertible to std::string.
You can obtain the same thing, mixing overloading and template, obtaining a compilation (not linking) error as follows
#include <string>
template <typename T>
void foo (T const &) = delete;
void foo (std::string const &)
{ }
int main ()
{
foo("abc");
}
Now the non-template foo() can (theoretically) accept a char cont [4], but is declared (and deleted) the template version. So, given again that char const [4] isn't a std::string, the compiler give the precedence to the template version. That is deleted. So the compilation error.