Search code examples
c++enumsforward-declaration

Enum Forward Declaration


I'm trying to correctly use a forward declaration for enums. Therefore I searched the Internet, but I can't find something that works.

I'm using this in a header:

// Forward declaration
enum myEnumProcessState;

I'm then using this enum in a struct:

struct myStruct {
    [...]
    myEnumProcessState osState;
    [...]
};

And in another header:

enum myEnumProcessState {
    eNotRunning,
    eRunning
};

I found out that the type should be put in the enum forward declaration to be accepted. However, I don't know which "type" I should put for a Process State. These don't work:

enum myEnumProcessState : unsigned int;
enum myEnumProcessState : String;

I wanted to skip the forward declaration, but my struct is crying since it can't find it any more...

So I'm a bit confused. Is there a solution?


Solution

  • Before C++11, C++ didn't support forward-declaration of enums at all! However, some compilers (like MS Visual Studio) provide language extensions for that.

    If your compiler doesn't support C++11, look in its documentation on enum forward declarations.

    If you can use C++11, there is the enum class syntax (you almost got it right, but pay attention to the additional class keyword:

    // Forward declaration
    enum class myEnumProcessState: unsigned int;
    
    // Usage in a struct
    struct myStruct {myEnumProcessState osState;};
    
    // Full declaration in another header
    enum class myEnumProcessState: unsigned int {
        eNotRunning,
        eRunning
    };
    
    // Usage of symbols (syntax may seem slightly unusual)
    if (myObject.osState == myEnumProcessState::eNotRunning) {
        ...
    }