26

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 ?

tommyk
  • 3,187
  • 7
  • 39
  • 61
  • 1
    How about forward declaring the class before enum such `class Foo;`? – Fredrick Gauss Nov 19 '14 at 14:29
  • 1
    I doubt it. You can't forward declare member functions, typedefs, ect. Why would this be any different? (C++ classes are closed, meaning they can't be edited after defition.) See also http://stackoverflow.com/questions/836551/forward-declare-a-classs-public-typedef-in-c – IdeaHat Nov 19 '14 at 14:30
  • Unlike classes, namespaces can be added to from anywhere. Why not put the enum and the class into a namespace? – Khouri Giordano Nov 19 '14 at 14:38
  • 1
    Possible duplicate of [C++ Forward declaring class scoped enumeration](http://stackoverflow.com/questions/13842006/c-forward-declaring-class-scoped-enumeration), related http://stackoverflow.com/questions/2238170/forward-declaration-of-nested-enum – Ciro Santilli OurBigBook.com Dec 18 '16 at 11:28

2 Answers2

15

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.

Columbo
  • 60,038
  • 8
  • 155
  • 203
6

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.

Jeremy
  • 5,055
  • 1
  • 28
  • 44