Declare enum without defining

How do you declare an enum without defining it? The enum in question looks like
 
enum Beer {Carlsburg, Tuborg, Thor }; 
Same question for namespace like
 
namespace NS { int a}
Last edited on
To use Beer::Carlsburg, you need to define Carlsburg. TO use NS::a, you need to define int a. I think you can forward declare an enum or namespace, but you can't use anything inside of it without defining that content.

What are you trying to do? I can see that you might be trying to remove content from header-files and reduce what you've exposed to the outside world. If that's the case, check out the pimpl methodology.

1
2
3
4
5
6
7
8
9
10
// MyClass.h
class MyImpl; // This contains your core class

class MyClass
{
    MyImpl *pimpl;
public:
   MyClass();
   void SomeMethod();
}


1
2
3
4
5
6
7
8
9
10
11
12
13
// MyClass.cpp
#include "MyClass.h"
#include "MyImpl.h" // Here we get the full class

MyClass::MyClass()
{
    pimpl = new MyImpl();
}

void MyClass::SomeMethod() // This just calls the pimpl function.
{
    pimpl->someMethod(); 
}

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
namespace NS
{
    enum Beer : int ; // declare Beer; the underlying type of the enum
                      // (int in this example) must be specified (C++11)

    // note: in the bad old days, an enum could not be forward declared
    // the size of the underlying integral type was not known till its definition was seen

    extern int a ; // declare A as an int with external linkage
}

struct A
{
    A( NS::Beer f, int v = NS::a ) : favourite(f), value(v) {}

    bool is_favourite( NS::Beer b ) const { return b == favourite ; }

    void foo() ;

    NS::Beer favourite ;
    int value ;
};

namespace NS
{
    enum Beer : int { Carlsburg, Tuborg, Thor } ; // define Beer
}

void A::foo()
{
    switch( favourite )
    {
        // requires that the definition of NS::Beer has been seen by now
        case NS::Carlsburg :
           NS::a += 5 ;
           break ;

        // ...

        default:

        ++NS::a ;
        // ...
    }
}

// somewhere else, may be in another translation unit:
namespace NS
{
    int a = 72 ; // define a
}
Last edited on
You can use opaque enum declaration. For example

enum Beer : int;

or

enum class Beer;




How do you declare an enum without defining it?

Note that JLBorges mentions C++11 in this code comments.

Before C++11 it was impossible to forward declare an enum in ANSI C++

Andy
Last edited on
Topic archived. No new replies allowed.