Function Template Partial Specialization in C : An Explanation
In C , function template partial specialization is not permitted by the standard. However, certain compilers, such as Microsoft Visual Studio 2010 Express, may allow partial specialization as an extension.
Partial specialization of function templates involves defining a specific implementation for a template with a particular set of arguments. Unlike class templates, which allow both full and partial specialization, function templates support only full specialization.
Consider the following code:
template <typename T1, typename T2> inline T1 max(T1 const& a, T2 const& b) { return a < b ? b : a; } template <typename T> inline T const& max(T const& a, T const& b) { return 10; }
This code appears to partially specialize the max function template for arguments of the same type. However, this is not actually a case of partial specialization. Instead, the second function template is an overloaded version of the first, with the same name but different parameter types.
The syntax for a partial specialization of a function template, if it were allowed, would resemble the following:
template <typename T> inline T const& max<T, T>(T const& a, T const& b) { return a; }
In the provided code, the second max function is overloaded to handle cases where both arguments have the same type. This is not a partial specialization but rather an overloading based on argument types.
It's important to note that compilers that support function template partial specialization may allow code that does not conform to the C standard. Portable code should avoid relying on such extensions.
The above is the detailed content of Why Doesn't C Allow Partial Specialization of Function Templates?. For more information, please follow other related articles on the PHP Chinese website!