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 o开发者_开发技巧f?
Prefer overload over function specialization, says Herb Sutter. He explains this in his articles:
- Why Not Specialize Function Templates?
- Template Specialization and Overloading
Always choose an overload if you can. Function template specialization is a fickle bitch. For example, no implicit conversions are considered, including covariance, when deciding about specializations.
Edit: For example, if you do something like,
template<typename T> void func(T t);
template<> void func(base*);
int main() {
func(new derived);
}
The specialization will not be called. If it were an overload, it would be called.
精彩评论