Syntax for partial class template specialization

狂风中的少年 提交于 2019-12-13 05:18:30

问题


In the following, am I forgetting some correct syntax for partial specializing class NumInfo or is it even possible to do that?

template<typename T>
struct NumInfo {
    T x;
    T y;

    void Print();
};

template<typename T>
void NumInfo <T>::Print() {
    /*.....*/
}

template<typename T>
struct NumInfo <float> {
    T x;
    float y;

    void Print();
};

template<typename T>
void NumInfo <float>::Print() {
    /*.....*/
}

回答1:


Your design has a problem -- right now you have multiple classes with the same name NumInfo<float> and different definitions (depending on T). To fix that, you'll need a second template parameter, like this:

template<typename S, typename T=S>
struct NumInfo
{
    T x;
    S y;

    void Print();
};

template<typename S, typename T>
void NumInfo<S,T>::Print()
{
    /*.....*/
}

template<typename T>
struct NumInfo<float,T>
{
    T x;
    float y;

    void Print();
};

template<typename T>
void NumInfo<float,T>::Print()
{
    /*.....*/
}



回答2:


template<typename T>
struct NumInfo {
    T x;
    T y;

    void Print();
};

template<typename T>
void NumInfo <T>::Print() {
    /*.....*/
}

template<>
struct NumInfo <float> {
    typedef float T;
    T x;
    float y;

    void Print();
};

void NumInfo <float>::Print() {
    /*.....*/
}


来源:https://stackoverflow.com/questions/7755244/syntax-for-partial-class-template-specialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!