Suppose I have a function template:
template <typename T>
std::string foo(const T& x)
{
return some_computation_involving(x);
}
If x is already a string, I just want to pass it back verbatim. Should I specialize the function template?
template <>
std::string foo(const std::string& x)
{
return x;
}
Or should I provide a non-template function?
std::string foo(const std::string& x)
{
return x;
}
Under what circumstances should I choose which option, and what are the pitfalls I need to be aware of?
Prefer overload over function specialization, says Herb Sutter. He explains this in his articles: