Explicit Specialization of Template Function in Template Class in C
In C , when working with template classes and functions, it may be necessary to explicitly specialize a template function within a template class. However, finding the correct syntax for this can be challenging.
Consider the following code:
struct tag {}; template< typename T > struct C { template< typename Tag > void f( T ); // declaration only template<> inline void f< tag >( T ) {} // ERROR: explicit specialization in non-namespace scope };
This code, which compiles successfully in Visual C 2008 but fails in GCC 4.2, attempts to explicitly specialize the f function for the tag type within the C template class. The compiler error indicates that explicit specialization is not allowed in a non-namespace scope within the template class.
The correct way to explicitly specialize a template function within a template class is to forward calls to a member function of a partially specialized type. This can be done using a helper class:
template<class T, class Tag> struct helper { static void f(T); }; template<class T> struct helper<T, tag1> { static void f(T) {} }; template<class T> struct C { // ... template<class Tag> void foo(T t) { helper<T, Tag>::f(t); } };
In this code, helper is a template class with two template parameters: T (the type of the object being operated on) and Tag (the specialization tag). A partially specialized version of helper is defined for the tag1 specialization, which provides the implementation for the f function. The C template class then uses a member function foo to delegate calls to the appropriate helper
The above is the detailed content of How to Correctly Explicitly Specialize a Template Function within a C Template Class?. For more information, please follow other related articles on the PHP Chinese website!