Explicit Specialization of Template Functions in Template Classes: Syntax Conundrum in C
The given code snippet exemplifies a programming conundrum that arises when attempting to explicitly specialize a template function within a template class. In Microsoft Visual C 2008 (VC9), the code compiles successfully; however, the same code encounters an error when compiled using GCC 4.2 on a Mac.
GCC requires explicit specializations to be declared outside the class, but the correct syntax for doing so is unclear. The initial attempt at placing the explicit specialization outside the class, as shown below, is incorrect:
template< typename T > template<> inline void C< T >::f< tag >( T ) {}
The correct approach involves forwarding calls to a member function of a partially specialized type. Here's the corrected code:
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); } };
This modification introduces a helper structure that provides the desired functionality while adhering to the syntax requirements of GCC. By separating the explicit specialization from the class itself, the code compiles successfully and functions as expected.
The above is the detailed content of How to Correctly Explicitly Specialize Template Functions within Template Classes in C ?. For more information, please follow other related articles on the PHP Chinese website!