Sign in to follow this  

Specializing template member function of template class

This topic is 4068 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
As a side note, you can use partial specialization on classes to achieve this:


// Forward declaration of C
template<class T> class C;

// A class that defines the function
template<class A,class T>
class Dud {
public:
static void f(C<T>&) { std::cout << "unspec\n"; }
};

// Specialization for A = int
template<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 action
template <class T>
class C {
public:
template <class A> void f() { Dud<A,T>::f(*this); }
};

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4068 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this