嵌套类模板专门化

nik*_*ack 17 c++ templates template-specialization

一类:

template<typename C, typename T>
class A
{
    template <typename U>
    class Nested{};

    Nested<T> n;
};
Run Code Online (Sandbox Code Playgroud)

我想专攻Nested.这是我尝试过的:

template<typename C, typename T>
class A
{
    template <typename U>
    class Nested{};

    template <>
    class Nested<int>{}; // by my logic this should work by I have a compilation error "explicit specialization in non-namespace scope 'class A<C, T>'"

    Nested<T> n;
};
Run Code Online (Sandbox Code Playgroud)

我的下一次尝试:

template<typename C, typename T>
class A
{
    template <typename U>
    class Nested{};

    Nested<T> n;
};

template<>
A<>::Nested<int>{}; // What is the correct syntax to do it here? Now I have an error "wrong number of template arguments (0, should be 2)"
Run Code Online (Sandbox Code Playgroud)

在stackoverflow上我找到了一个解决方案:

template<typename C, typename T>
class A
{
    template <typename U, bool Dummy = true>
    class Nested{}; // why need of this Dummy??

    template <bool Dummy>
    class Nested<int, Dummy>{}; // why need to provide an argument??

    Nested<T> n;
};
Run Code Online (Sandbox Code Playgroud)

它完美有效,但我无法理解.为什么要提供虚拟模板参数?为什么我不能使用原始专业化template<> class Nested<int, true>{}template<> class Nested<int>{}

For*_*veR 20

禁止在类范围中创建显式特化:

应在包含专用模板的命名空间中声明显式特化.

但是不禁止创建部分专业化:

可以在任何可以定义其定义的命名空间范围中声明或重新声明类模板部分特化(14.5.1和14.5.2).

这个

template <bool Dummy>
class Nested<int, Dummy>{}; // why need to provide an argument??
Run Code Online (Sandbox Code Playgroud)

是部分特化,允许在类范围内创建这种特化.在非专用的外部类中,您也无法完全专门化嵌套类.你可以这样做:

template<>
template<>
class A<int, double>::Nested<int>
{
};
Run Code Online (Sandbox Code Playgroud)

但你做不到

template<typename C, typename T>
template<>
class A<C, T>::Nested<int>
{
};
Run Code Online (Sandbox Code Playgroud)