Search code examples
c++templatesspecializationpartial-specialization

Partial specialization of specific member functions


#include <iostream>

template <typename T1, typename T2>
class B{
public:
    void update(){ std::cerr<<__PRETTY_FUNCTION__<<std::endl; }
    void func1(){ std::cerr<<__PRETTY_FUNCTION__<<std::endl; }
    void func2(){ std::cerr<<__PRETTY_FUNCTION__<<std::endl; }
};

template <typename T1>
class B<T1, int>{
public:
    void update(){ std::cerr<<__PRETTY_FUNCTION__<<"(specialization)"<<std::endl;}
};

int main(){
    B<int, double> b1;
    b1.update();
    b1.func1();
    B<int, int> b2;
    b2.update();
    //b2.func1();//there's no function 'func1' in B<int,int>
}

I want to specialize update function for specific template parameter(data type).

So I tried to specialize template class B but it seems that I have to implement whole member functions again.

Because other members are exactly same between specializations, reimplementing whole members look cumbersome.

Is there any workaround for this case?


Solution

  • Tag-dispatch the call to update:

    template <typename> struct tag {};
    
    template <typename T1, typename T2>
    class B
    {
    public:
        void update()
        {
            return update(tag<B>());
        }
    
    private:
        template <typename U1>
        void update(tag<B<U1, int> >)
        {
            // specialization
        }
    
        template <typename U1, typename U2>
        void update(tag<B<U1, U2> >)
        {
            // normal
        }
    };
    

    DEMO