【问题标题】:Partial specialization of specific member functions特定成员函数的部分特化
【发布时间】:2016-05-30 18:24:41
【问题描述】:
#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>
}

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

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

因为专精之间的其他成员完全相同,重新实现整个成员看起来很麻烦。

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

【问题讨论】:

标签: c++ templates specialization partial-specialization


【解决方案1】:

将调用标记为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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2012-04-11
    • 2021-04-16
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多