Ru-Brd |
In Chapter 12 we discussed how class templates can be partially specialized, whereas function templates are simply overloaded. The two mechanisms are somewhat different. Partial specialization doesn't introduce a completely new template: It is an extension of an existing template (the primary template). When a class template is looked up, only primary templates are considered at first. If, after the selection of a primary template, it turns out that there is a partial specialization of that template with a template argument pattern that matches that of the instantiation, its definition (in other words, its body ) is instantiated instead of the definition of the primary template. (Full template specializations work exactly the same way.) In contrast, overloaded function templates are separate templates that are completely independent of one another. When selecting which template to instantiate, all the overloaded templates are considered together, and overload resolution attempts to choose one as the best fit. At first this might seem like an adequate alternative, but in practice there are a number of limitations:
Together, this list forms a compelling argument in support of a partial specialization construct for function templates. A natural syntax for partially specializing function templates is the generalization of the class template notation: template <typename T> T const& max (T const&, T const&); // primary template template <typename T> T* const& max <T*>(T* const&, T* const&); // partial specialization Some language designers worry about the interaction of this partial specialization approach with function template overloading. For example: template <typename T> void add (T& x, int i); // a primary template template <typename T1, typename T2> void add (T1 a, T2 b); // another (overloaded) primary template template <typename T> void add<T*> (T*&, int); // which primary template does this specialize? However, we expect such cases would be deemed errors without major impact on the utility of the feature. At the time of this writing, this extension is under consideration by the C++ standardization committee. |
Ru-Brd |