问题
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