【问题标题】:How to specialize a nested class for template template parameter of the enclose class如何为封闭类的模板模板参数专门化一个嵌套类
【发布时间】:2021-02-16 21:08:46
【问题描述】:

给定:

template<typename T> 
struct Foo
{
    template<typename U>
    struct Bar {};

    /* many more members */
}

template<typename F> 
struct Zoo {};

我需要只有 Bar 将专门用于当封闭类 Foo 的类型为 Foo&lt;Zoo&lt;F&gt;&gt; 时,无论 F 是什么。 我不想将 Foo 部分专门化为 Zoo&lt;F&gt;,因为我需要再次声明它的所有成员。

我不明白为什么以下内容无法编译:

template<typename F>
template<typename U>
struct Foo<Zoo<F>>::Bar {}

因为我希望 Foo&lt;Zoo&lt;F&gt;&gt; 被视为主要的 Foo 模板,其模板参数设置为 Zoo&lt;F&gt;,并且只有 Bar 应该是专门的。

【问题讨论】:

    标签: templates nested template-specialization template-templates


    【解决方案1】:

    一位朋友给了我解决方案,我分享了。

    根据c++标准:

    “每个类模板部分特化都是一个不同的模板,并且为模板部分特化的成员提供定义外壳”

    这就是代码无法编译的原因。 Foo&lt;Zoo&lt;F&gt;&gt; 是 Foo 的部分特化,在这种情况下,根据 C++ 标准,编译器不使用主模板,但期望有一个不同的定义。

    解决方案一:定义封闭类的部分特化

    我们必须首先定义 Foo&lt;Zoo&lt;F&gt;&gt; 的特化,但如果我们已经定义了它,那么我们实际上可以在这个定义中特化 Bar。

    // partial specialization of Foo 
    template<typename T> 
    struct Foo<Zoo<T>>
    {
        template<typename U>
        struct Bar { /* specialize declaration for Bar here */ };
    
        /* many more members - should be define here as in the primary template of Foo */
    };
    

    这将给出预期的结果,但问题是我们必须在特化中再次定义所有 Foo 其他成员。

    解决方案 2:将嵌套类的声明移动到基类中

    // base class contains only declaration of Bar
    template<typename T> 
    struct FooBase
    {
        template<typename U>
        struct Bar {};
    };
    
    // Foo contains other members, but also derived from FooBase
    template<typename T> 
    struct Foo : public FooBase<T>
    {
        /* many members */
    };
    

    为了在 Foo 的类型为 Foo&lt;Zoo&lt;T&gt;&gt; 时特化 Bar,我们定义了 FooBase 的部分特化。

    // partial specialization of FooBase 
    template<typename T> 
    struct FooBase<Zoo<T>>
    {
        template<typename U>
        struct Bar { /* specialize declaration for Bar here */ };
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多