Suppose I have a function template where the type parameter is used as a return type only:
template <typename T>
T foo()
{
return whatever;
}
Then what is the correct syntax to specialize that function template? Both of the following seem to work:
template <>
std::string foo()
{
return whatever;
}
template <>
std::string foo<std::string>()
{
return whatever;
}
Is there any difference between the two? If not, what is the idiomatic way?
The compiler will deduce the correct template specialization based on informations provided (here, the function return type).
So these syntaxes have exactly the same behaviour, one being more explicit than the other.
In most case, there is no difference between the two.
If you overload several template functions, the second form may be needed to remove an ambiguity about which overload you mean to specialize (you probably have other problems if you are in this situation, for instance you'll also need to be explicit at call places).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With