Template class member specialization

Possible duplicate:
Specialization of a member function in a template 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 the template method of the template class?

+6
source share
1 answer

This cannot be done upon request. For some reason (I'm not sure about the rationale), explicit (i.e. full) specialization of a member template is allowed only when the enclosing class is also explicitly (i.e. completely) specialized. This requirement is explicitly stated 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 temporary solution (albeit ugly). But, obviously, it applies only to member class templates. When it comes to member function templates, an alternative solution must be used.

For example, a possible workaround is to delegate the call to the static member of the template class and instead specialize the class (which is often recommended as a better idea than specializing 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(); } }; 
+13
source

Source: https://habr.com/ru/post/913346/


All Articles