Using member class template specialization in the class

  c++, c++17

Is there a standard complying way of using member class template specialization in the same class?

struct S {
    template<typename T> struct Data;
    template<> struct Data<char> {};
    template<> struct Data<int> {};

    Data<char> d1;
    Data<int> d2;
};

doesn’t work because full specializations of member class template are not allowed inside the class. Some compilers chose to ignore the holy standard in that case and are happy with that code, but some are following the rules.

struct S {
    template<typename T> struct Data;
    Data<char> d1;
    Data<int> d2;
};

template<> struct S::Data<char> {};
template<> struct S::Data<int> {};

doesn’t work either because specializations can’t be used before they are defined.

I understand that I can move member class template out of the class, but that’s beside the point.

Stupidly enough, I can work around the prohibition on in-class template specialization if I use an additional template parameter just for that reason:

struct S {
    template<typename T, typename NotUsed = void> struct Data;
    template<typename NotUsed> struct Data<char, NotUsed> {};
    template<typename NotUsed> struct Data<int, NotUsed> {};

    Data<char> d1;
    Data<int> d2;
};

Now it’s fine because partial template specialization is allowed inside the class.

Am I missing some way of doing it "the right way" – making specialization outside the class and still be able to use it inside? I am assuming C++17 version of the standard.

Source: Windows Questions C++

LEAVE A COMMENT