c++templatespartial-classes

C++ partial method specialization


Is there a partial specialization for template class method?

 template <class A, class B>
 class C
 {
  void foo();
 }

it doesn't work to specialize it like this:

template <class A> void C<A, CObject>::foo() {};

Any help?


Solution

  • If you are already have specialized class you could give different implementation of foo in specialized class:

    template<typename A, typename B>
    class C
    {
    public:
        void foo() { cout << "default" << endl; };
    };
    
    template<typename A>
    class C<A, CObject>
    {
    public:
      void foo() { cout << "CObject" << endl; };
    };
    

    To specialize member function in Visual C++ 2008 you could make it template too:

    template<typename A, typename B>
    class C
    {
      template<typename T>
      void foo();
    
      template<>
      void foo<CObject>();
    };
    

    The solution above seems to will be available only in future C++ Standard (according to draft n2914 14.6.5.3/2).