Jump to content
  • Advertisement
Sign in to follow this  
snooty

Specializing template member function of template class

This topic is 4354 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
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?

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!