Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specializing a templated member of a template class [duplicate]

Tags:

c++

templates

Possible Duplicate:
Specialization of templated member function in templated class

template <class T>    
class MyClass
{
   template <int N>
   void func() {printf("unspecialized\n");}
};
template<class T>
template<>
MyClass<T>::func<0>()
{
   printf("specialzied\n");
}

This does not work. Is it possible to specialize a template method of an template class?

like image 264
Alexander Vassilev Avatar asked Apr 16 '12 17:04

Alexander Vassilev


People also ask

Can a non templated class have a templated member function?

A non-template class can have template member functions, if required. Notice the syntax. Unlike a member function for a template class, a template member function is just like a free template function but scoped to its containing class.

What is function template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

Why does the need of template specialization arise?

It is possible in C++ to get a special behavior for a particular data type. This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming.


1 Answers

It cannot be done as requested. For some reason (I'm not sure about the rationale) explicit (i.e full) specialization of a member template is only allowed when the enclosing class is also explicitly (i.e fully) specialized. This requirement is explicitly spelled out in the language standard (see 14.7.3/18 in C++98, C++03 and 14.7.3/16 in C++11).

At the same time, partial specializations of member class templates are allowed, which in many cases can be used as a workaround (albeit an ugly one). But, obviously, it is only applicable to member class templates. When it comes to member function templates, an alternative solution has to be used.

For example, a possible workaround is to delegate the call to a static member of a template class and specialize the class instead (which is often recommended as a better idea than specialization of function templates http://www.gotw.ca/publications/mill17.htm)

template <class T>    
class MyClass
{
   template <int N, typename DUMMY = void> struct Func {
     static void func() { printf("unspecialized\n"); }
   };

   template <typename DUMMY> struct Func<0, DUMMY> {
     static void func() { printf("specialized\n"); }
   };

   template <int N> void func() { Func<N>::func(); }
};
like image 165
AnT Avatar answered Oct 25 '22 12:10

AnT