3

If I have:

template <typename T>
bool name (std::string);

template <> bool name<int>(std::string);

What is the difference between the fully specialized function and my other regular functions.

For example in the header I would have to have these declarations plus the template definition; nevertheless I can have the specialized definition in a source file along all the other regular functions. Are them the same?

Is that a better practice than having the definition of the specialized template as inline in the header?

Daniel Duque
  • 159
  • 9
  • The specialization must be seen (before code that use it) to be effective so usually need to be in an header. – Phil1970 Feb 11 '19 at 02:13

1 Answers1

0

A function template specialization determines the effect of a call when the template itself is selected by overload resolution (which uses the signature, but not the definition, of the specialization). This is true whether the specialization is implicitly or explicitly generated.

A separate function participates in overload resolution on its own, competing with the function template at a slight advantage that can easily be offset by template argument deduction (though not here, since your T cannot be deduced). It can be excluded entirely by using an explicit template argument list (even an empty one if all template arguments can be deduced), which means the template should still be given a sensible definition for all types (even if some are deleted or otherwise do not compile).

As for inline, the concerns are no different from those for any function: providing the definition in the header can be important for optimization, allow a header-only library, reduce textual repetition, …or merely produce tighter coupling that makes the code harder to change. Since the definition of the primary template must usually be in the header, there is perhaps a bias toward putting the definition of the specialization there as well. As always, knowledge of the application and judgment is required.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76