Forward declaring an enum in C++

2019-01-02 14:41发布

I'm trying to do something like the following:

enum E;

void Foo(E e);

enum E {A, B, C};

which the compiler rejects. I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why. Can anyone explain?

Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I do not want the enum's values exposed - so, for example, I do not want anyone to know that E is defined as

enum E {
    FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X
}

as project X is not something I want my users to know about.

So, I wanted to forward declare the enum so I could put the private methods in the header file, declare the enum internally in the cpp, and distribute the built library file and header to people.

As for the compiler - it's GCC.

标签: c++ enums
18条回答
公子世无双
2楼-- · 2019-01-02 14:59

The reason the enum can't be forward declared is that without knowing the values, the compiler can't know the storage required for the enum variable. C++ Compiler's are allowed to specify the actual storage space based on the size necessary to contain all the values specified. If all that is visible is the forward declaration, the translation unit can't know what storage size will have been chosen - it could be a char or an int, or something else.


From Section 7.2.5 of the ISO C++ Standard:

The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of sizeof() applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of sizeof() applied to the underlying type.

Since the caller to the function must know the sizes of the parameters to correctly setup the call stack, the number of enumerations in an enumeration list must be known before the function prototype.

Update: In C++0X a syntax for foreward declaring enum types has been proposed and accepted. You can see the proposal at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf

查看更多
公子世无双
3楼-- · 2019-01-02 15:01

There is indeed no such thing as a forward declaration of enum. As an enum's definition doesn't contain any code that could depend on other code using the enum, it's usually not a problem to define the enum completely when you're first declaring it.

If the only use of your enum is by private member functions, you can implement encapsulation by having the enum itself as a private member of that class. The enum still has to be fully defined at the point of declaration, that is, within the class definition. However, this is not a bigger problem as declaring private member functions there, and is not a worse exposal of implementation internals than that.

If you need a deeper degree of concealment for your implementation details, you can break it into an abstract interface, only consisting of pure virtual functions, and a concrete, completely concealed, class implementing (inheriting) the interface. Creation of class instances can be handled by a factory or a static member function of the interface. That way, even the real class name, let alone its private functions, won't be exposed.

查看更多
公子世无双
4楼-- · 2019-01-02 15:01

If you really don't want your enum to appear in your header file AND ensure that it is only used by private methods, then one solution can be to go with the pimpl principle.

It's a technique that ensure to hide the class internals in the headers by just declaring:

class A 
{
public:
    ...
private:
    void* pImpl;
};

Then in your implementation file (cpp), you declare a class that will be the representation of the internals.

class AImpl
{
public:
    AImpl(A* pThis): m_pThis(pThis) {}

    ... all private methods here ...
private:
    A* m_pThis;
};

You must dynamically create the implementation in the class constructor and delete it in the destructor and when implementing public method, you must use:

((AImpl*)pImpl)->PrivateMethod();

There are pros for using pimpl, one is that it decouple your class header from its implementation, no need to recompile other classes when changing one class implementation. Another is that is speeds up your compilation time because your headers are so simple.

But it's a pain to use, so you should really ask yourself if just declaring your enum as private in the header is that much a trouble.

查看更多
听够珍惜
5楼-- · 2019-01-02 15:03

My solution to your problem would be to either:

1 - use int instead of enums: Declare your ints in an anonymous namespace in your CPP file (not in the header):

namespace
{
   const int FUNCTIONALITY_NORMAL = 0 ;
   const int FUNCTIONALITY_RESTRICTED = 1 ;
   const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;
}

As your methods are private, no one will mess with the data. You could even go further to test if someone sends you an invalid data:

namespace
{
   const int FUNCTIONALITY_begin = 0 ;
   const int FUNCTIONALITY_NORMAL = 0 ;
   const int FUNCTIONALITY_RESTRICTED = 1 ;
   const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;
   const int FUNCTIONALITY_end = 3 ;

   bool isFunctionalityCorrect(int i)
   {
      return (i >= FUNCTIONALITY_begin) && (i < FUNCTIONALITY_end) ;
   }
}

2 : create a full class with limited const instantiations, like done in Java. Forward declare the class, and then define it in the CPP file, and instanciate only the enum-like values. I did something like that in C++, and the result was not as satisfying as desired, as it needed some code to simulate an enum (copy construction, operator =, etc.).

3 : As proposed before, use the privately declared enum. Despite the fact an user will see its full definition, it won't be able to use it, nor use the private methods. So you'll usually be able to modify the enum and the content of the existing methods without needing recompiling of code using your class.

My guess would be either the solution 3 or 1.

查看更多
牵手、夕阳
6楼-- · 2019-01-02 15:04

Forward declaration of enums is also possible in C++0x. Previously, the reason enum types could not be forward declared is because the size of the enumeration depends on its contents. As long as the size of the enumeration is specified by the application, it can be forward declared:

enum Enum1;                   //Illegal in C++ and C++0x; no size is explicitly specified.
enum Enum2 : unsigned int;    //Legal in C++0x.
enum class Enum3;             //Legal in C++0x, because enum class declarations have a default type of "int".
enum class Enum4: unsigned int; //Legal C++0x.
enum Enum2 : unsigned short;  //Illegal in C++0x, because Enum2 was previously declared with a different type.
查看更多
临风纵饮
7楼-- · 2019-01-02 15:04

In answer to the clarification: If you use the enum internally only, why not declare it inside the class as private?

查看更多
登录 后发表回答