首页 文章

定义专用类的不完整结构

提问于
浏览
3

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

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

2 回答

  • -3

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

    如果类头名包含嵌套名称指定者,则类指定者应引用先前在嵌套名称指定者所引用的类或命名空间中直接声明的类,或者在该命名空间的内联命名空间集(7.3.1)(即,不仅仅是由using声明继承或引入),并且类指定符应出现在包含前一个声明的命名空间中 . 在这种情况下,定义的类头名的嵌套名称指定者不应以decltype-speci fi er开头 .

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

相关问题