【问题标题】:Defining incomplete struct of specialized class定义专业类的不完整结构
【发布时间】:2013-07-19 09:49:42
【问题描述】:

我在类特化中声明一个不完整的结构并稍后定义它时遇到问题。

struct Foo {
    template <bool Y, typename D>
    struct Bar {};

    template <typename D>
    struct Bar<true, D> {
        struct Qux;
    };

    template <typename D>
    struct Bar<true, D>::Qux { int x; };
};

此代码在 gcc 中有效,但在 clang 3.3 中失败:

r.cpp:42:26: error: non-friend class member 'Qux' cannot have a qualified name
    struct Bar<true, D>::Qux { int x; };
           ~~~~~~~~~~~~~~^

如果代码是在命名空间范围内编写的(没有struct Foo),它也可以在clang中工作。

另一方面,如果将struct Foo 转换为模板,如下所示,代码在 gcc-4.9(未发布)中中断,尽管它在 gcc-4.7 中继续工作。

template <typename X>
struct Foo {
    template <bool Y, typename D>
    struct Bar {};

    template <typename D>
    struct Bar<true, D> {
        struct Qux;
    };

    template <typename D>
    struct Bar<true, D>::Qux { int x; };
};

Clang 失败:

r.cpp:43:26: error: template specialization or definition requires a template parameter list corresponding to the nested type 'Bar<true, type-parameter-1-0>'
    struct Bar<true, D>::Qux { int x; };
                         ^
r.cpp:43:26: error: non-friend class member 'Qux' cannot have a qualified name
    struct Bar<true, D>::Qux { int x; };
           ~~~~~~~~~~~~~~^
2 errors generated.

Gcc-4.9 失败并出现类似错误:

r.cpp:43:26: error: too few template-parameter-lists
     struct Bar<true, D>::Qux { int x; };
                          ^

【问题讨论】:

    标签: c++ specialization incomplete-type


    【解决方案1】:

    看起来您别无选择,只能将该定义放在命名空间范围内(或在 Bar 内)。第 9/1 段 (n3337) 说您的代码是非法的:

    如果一个 class-head-name 包含一个 nested-name-specifier,则 class-specifier应该指的是一个类 之前直接在 nested-name-specifier 引用的类或命名空间中声明,或者在 该命名空间的内联命名空间集 (7.3.1) 的元素(即,不仅仅是继承或引入 using-declaration),并且 class-specifier 应出现在包含先前声明的命名空间中。 在这种情况下,定义的 class-head-namenested-name-specifier 不应以 decltype-specifier.

    【讨论】:

      【解决方案2】:
      struct Foo {
        template <bool Y, typename D>
        struct Bar {};
      };
      
      template <typename D>
      struct Foo::Bar<true, D> {
        struct Qux;
      };
      
      template <typename D>
      struct Foo::Bar<true, D>::Qux {
        int x;
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-26
        • 2016-01-21
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 2023-01-13
        相关资源
        最近更新 更多