Search code examples
c++templatespartial-specialization

partial template member specialization


Given the following definitions:

template <typename T>
class A {

public:

   void f();

};

template <typename T>
void
A<T>::f()
{}

template <typename T>
class B {};

How would I partially specialize A<B<T>>::f, i.e. f for some B<T>? I'm basically looking for the right magic to substitute the ??? below

template <???>
void
A<B<T>>::f()
{}

Solution

  • You can have an explicit specialization, from [temp.expl.spec]:

    An explicit specialization of any of the following:
    — ...
    — member function of a class template
    — ...
    can be declared by a declaration introduced by template<>

    That is:

    template <>
    void A<B<int>>::f() {
        std::cout << "B\n";
    }
    

    But you cannot have a partial specialization of a member function of a class template. You would have to partially specialize the entire class:

    template <typename T>
    class A<B<T>> {
    public:
        void f() {
            std::cout << "B\n";
        }
    
        // ... all other members you want in A<B<T>> ...
    };