嵌套类模板特化

时间:2015-10-13 09:42:06

标签: c++ templates template-specialization

一堂课:

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

    Nested<T> n;
};

我想专攻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;
};

我的下一次尝试:

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)"

在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;
};

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

2 个答案:

答案 0 :(得分:16)

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

  

应在包含的名称空间中声明显式特化   专业模板。

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

  

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

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

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

template<>
template<>
class A<int, double>::Nested<int>
{
};

但你做不到

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

答案 1 :(得分:1)

通过定义外部类中专用模板类的所有内容,我设法使其工作。所以所有函数都是用类定义完全定义的。没有外部函数定义,因为它似乎没有卷曲。即。

template <typename T, size_t N>
class A
{
private:
    template <size_t M>
    class B
    {
        ...
    };

    template <>
    class B<2>
    {
        ...
    };
    ... etc
};

至少在MS2015上有效。代码运行得很好。

相关问题