Partial Specialization of Function Templates: Why Not?
It is well-known that the C language specification prohibits partial specialization of function templates. This decision has puzzled many developers, who question its usefulness and rationale.
The language specification prohibits partial specialization of function templates because of an oversight. The flexibility offered by partial specialization can be achieved through alternative techniques, such as defining the function as a static member of a class.
For example, consider the following code:
template<typename T, typename U> void f() {} //allowed! template<> void f<int, char>() {} //allowed! template<typename T> void f<char, T>() {} //not allowed! template<typename T> void f<T, int>() {} //not allowed!
While partial specialization of f is not permitted, we can achieve a similar effect by defining the function as a static member of a class:
void say( char const s[] ) { std::cout << s << std::endl; } namespace detail { template< class T, class U > struct F { static void impl() { say( "1. primary template" ); } }; template<> struct F<int, char> { static void impl() { say( "2. <int, char> explicit specialization" ); } }; template< class T > struct F< char, T > { static void impl() { say( "3. <char, T> partial specialization" ); } }; template< class T > struct F< T, int > { static void impl() { say( "4. <T, int> partial specialization" ); } }; } // namespace detail template< class T, class U > void f() { detail::F<T, U>::impl(); } int main() { f<char const*, double>(); // 1 f<int, char>(); // 2 f<char, double>(); // 3 f<double, int>(); // 4 }
This code behaves similarly to partial specialization of function templates, providing a mechanism to define specialized implementations for specific argument combinations.
The above is the detailed content of Why are Partial Specializations of Function Templates Prohibited in C ?. For more information, please follow other related articles on the PHP Chinese website!