The question comes down to determining when specialization will be used so that overload cannot. There are different situations in which this occurs, although they are quite rare, and it is simple enough to make the mistake that the general recommendation is to prefer overloads to specializations.
When the caller explicitly requests the use of a template. In the code example that you specify, if the call is f<int>(42) or even f<42>() , then overload will not be used.
If you cannot provide the required congestion or congestion cannot be allowed at the place of call. For example, if the type is not one of the arguments of the function (it is generally absent in the signature or only in the return type:
pattern T f ();
In this case, you cannot provide overloads int f(); and double f(); , but you can provide as many specialized templates as you need, and the user will need to force one or the other. Please note that this can be considered as a subheading of the previous case: since the template arguments do not participate in the function arguments, the user needs to provide the template arguments, so the call is explicitly specified in the template.
If you want to set special restrictions on the combination of arguments and prohibit implicit conversions:
pattern void f (T, T); // Both arguments must be of the same type
Since the output of the template argument performs only perfect matches, this template can only be used if both arguments are of the same type, if you add overload void f(int,int) , that overload can be used with any combination of types that are implicit are converted to int, for example f( 5, 3.0 ) , but there will be no specialization.
In general, in most cases, none of the above cases apply, so overload is recommended.
There may be more, but these are the ones that I can recall from my head.
source share