Specializing template member function of template class

Started by
3 comments, last by Fruny 17 years, 6 months ago
How to specialize a template member function of a template class? template<typename T> class C { public: template<typename U> void foo(); }; template<typename T> template<> void C<T>::foo<int>() {} //doesn't work [Edited by - snooty on October 21, 2006 4:05:28 AM]
Advertisement
If I get the standard right, it's not possible.
That's because the function specialization is to be treated as a normal function definition, not as another template.

Quote:Standard draft (October 2005)

14.5.2 Member templates
[...]
[Example:
template <class T> struct A {  void f(int);  template <class T2> void f(T2);};template <> void A<int>::f(int) { };template <> template <> void A<int>::f<>(int) { };[...]

-- end Example]


There are only two examples of explicit specialization. Both require (at least) class template arguments to be specified.

Good news is that functions can be overloaded. Do you have to provide specialization - or could just plain good old overload do the job?
As a side note, you can use partial specialization on classes to achieve this:

// Forward declaration of Ctemplate<class T> class C;// A class that defines the functiontemplate<class A,class T> class Dud {public:  static void f(C<T>&) { std::cout << "unspec\n"; }};// Specialization for A = inttemplate<class T> class Dud<int,T> {public:  static void f(C<T>&) { std::cout << "spec\n"; }};// The actual C class calls Dud::f to perform the actiontemplate <class T>class C {public:  template <class A> void f() { Dud<A,T>::f(*this); }};
Strange that it's ok to do the specialization in the class definition.

Thanks anyway. :)
Quote:Original post by snooty
How to specialize a template member function of a template class?


If I remember correctly, you can't specialize the member without specializing the class. Specialization must be completed from the outside in. Foo<int>::Bar<T> is OK, Foo<T>::Bar<int> isn't.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement