Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ syntax for explicit specialization of a template function in a template class?

Tags:

c++

gcc

templates

I have code which works in VC9 (Microsoft Visual C++ 2008 SP1) but not in GCC 4.2 (on Mac):

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 'structC<T>' 

I understand that GCC would like me to move my explicit specialization outside the class but I can't figure out the syntax. Any ideas?

// the following is not correct syntax, what is? template< typename T > template<> inline void C< T >::f< tag >( T ) {} 
like image 499
jwfearn Avatar asked Jan 19 '10 22:01

jwfearn


People also ask

What is the syntax for explicit class specialization?

What is the syntax to use explicit class specialization? Explanation: The class specialization is creation of explicit specialization of a generic class. We have to use template<> constructor for this to work. It works in the same way as with explicit function specialization.

What is explicit template specialization?

Explicit (full) specializationAllows customizing the template code for a given set of template arguments.

What is the correct syntax of defining function template template functions?

6. What is the correct syntax of defining function template/template functions? Explanation: Starts with keyword template and then <class VAR>, then use VAR as type anywhere in the function below.

What is the syntax of template class?

1. What is the syntax of class template? Explanation: Syntax involves template keyword followed by list of parameters in angular brackets and then class declaration.


1 Answers

You can't specialize a member function without explicitly specializing the containing class.
What you can do however is forward calls to a member function of a partially specialized type:

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);     } }; 
like image 61
Georg Fritzsche Avatar answered Sep 20 '22 16:09

Georg Fritzsche