8

Is it possible to have a specialized template class which is a member of a template class(that is not specialized per se)?

With a non-template parent class this works:

class owner
{
    template<int num>
    struct s
    {
        int ret() { return num; }
    };
};

template<>
struct owner::s<0>
{
    int ret() { return 0; }
};

But when making owner a template class it does not:

template<typename some>
class owner
{
    template<int num>
    struct s
    {
        int ret() { return num; }
    };
};

template<typename some>
struct owner<some>::s<0>
{
    int ret() { return 0; }
};

Searching shows that this is not possible(?) for functions, but how about classes/structs? Specializing a templated member of a template class

Aart Stuurman
  • 3,188
  • 4
  • 26
  • 44

1 Answers1

6

No, that is not possible. A member class template can only be specialised if all of its enclosing class templates are also specialised. Quoting C++2x (N4713) [temp.expl.spec] 17.8.3/17:

In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.

(Emphasis mine)

In some cases, you could get around this by making the nested name s an alias to a namespace-scope helper which can be partially specialised. Something like this:

template <class some, int num>
struct s_helper
{
  int ret() { return num; }
};

template<typename some>
class owner
{
    template<int num>
    using s = s_helper<some, num>;
};

template<typename some>
struct s_helper<some, 0>
{
    int ret() { return 0; }
};

To reduce the exposure of s_helper, it can of course be hidden in a suitably named internal namespace (such as detail).

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455