2
#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?

JaeJun LEE
  • 1,234
  • 3
  • 11
  • 27
  • Possible duplicate of [c++ template partial specialization member function](http://stackoverflow.com/questions/15374841/c-template-partial-specialization-member-function) – LogicStuff May 30 '16 at 18:36

1 Answers1

5

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

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160