Is in-class enum forward declaration possible? [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-12-12 09:29:59

问题


I know that in C++11 it's possible to forward declare an enum type (if storage type is provided) e.g.

enum E : short;
void foo(E e);

....

enum E : short
{
    VALUE_1,
    VALUE_2,
    ....
}

But I would like to forward declare an enum defined within a class e.g.

enum Foo::E : short;
void foo(E e);

....

class Foo
{
    enum E : short
    {
        VALUE_1,
        VALUE_2,
    ....
    }
}

Is something like this possible in C++11 ?


回答1:


No, such a forward declaration isn't possible. [decl.enum]/5 (bold emphasis mine):

If the enum-key is followed by a nested-name-specifier, the enum-specifier shall refer to an enumeration that was previously declared directly in the class or namespace to which the nested-name-specifier refers (i.e., neither inherited nor introduced by a using-declaration), and the enum-specifier shall appear in a namespace enclosing the previous declaration.

(In this case the nested-name-specifier would be the name of your class followed by a ::.)
You could, though, put the enumeration outside and use an opaque-enum-declaration.




回答2:


As @Columbo says, you can't declare it in the form you specify.

You can, however, forward declare the nested enum inside the class declaration:

class Foo
{
    enum E : short;
};

void foo(Foo::E e);

enum Foo::E : short
{
     VALUE_1,
     VALUE_2,
    ....
};

Whether you gain any benefit by doing so depends, of course, on the circumstances.



来源:https://stackoverflow.com/questions/27019292/is-in-class-enum-forward-declaration-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!