Syntax for partial class template specialization

2019-08-29 03: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() {
    /*.....*/
}