特定成员函数的部分专业化

Jae*_*LEE 2 c++ templates partial-specialization specialization

#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>
}
Run Code Online (Sandbox Code Playgroud)

我想专门update针对特定模板参数(数据类型)的函数。

所以我尝试专业化template class B,但似乎我必须再次实现整个成员函数。

由于专业化之间的其他成员完全相同,因此重新实现整个成员看起来很麻烦。

对于这种情况有什么解决方法吗?

Pio*_*cki 5

将呼叫标记分派至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
    }
};
Run Code Online (Sandbox Code Playgroud)

演示版