MEMS MEMS - 18 days ago 5
C++ Question

Template specializations for inner class

consider the following code :

struct X
{
template <typename T>
class Y
{};
};
template<>
class X::Y<double>{
};


here we are specializing the Y class for the type double and the code works fine. the problem is that if I change the code to this:

template<typename A>
struct X
{
template <typename T>
class Y
{};
};
template<typename A>
class X<A>::Y<double>{
};


the compiler will report an error:


'X::Y': explicit specialization is using partial
specialization syntax, use template <> instead!


dose any one know how can I specialize class Y in this case?

Answer

You cannot specialize an inner template class without explicitly specializing the outer one as well. See this question for more details and a quote from the standard.

Workaround: create an outer class that takes both T and A in a detail namespace, and alias it inside X:

namespace impl
{
    template <typename A, typename T>
    struct Y { };
}

template<typename A>
struct X
{
    template <typename T>
    using Y = impl::Y<A, T>;
};

If you are fine with explicitly specializing both inner and outer class, you can use the following syntax:

template <>
template <>
class X<int>::Y<double>
{
    // ...
};

Example on wandbox

Comments