MEMS
MEMS

Reputation: 647

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?

Upvotes: 5

Views: 704

Answers (2)

W.F.
W.F.

Reputation: 13988

The simple answer - you can't fully specialize templated inner class of templated outer class. But if you really want to achieve similar effect you could try partial specialization with dummy defaulted template parameter:

#include <iostream>

template<typename A>
struct X
{
    template <typename T, T* =nullptr>
    class Y{};
 };

template<typename A>
template<double *Ptr>
class X<A>::Y<double, Ptr> {
public:
    static constexpr int value = 1;
};

int main() {
    std::cout << X<int>::Y<double>::value << std::endl;
}

[live demo]

Upvotes: 2

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

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

Upvotes: 4

Related Questions