When passing forward declared struct or a class, one has to pass it to a function through a reference or a pointer.
But, what can be done with a forward declared enum? Does it also have to be passed through a reference or a pointer? Or, can it be passed with a value?
Next example compiles fine using g++ 4.6.1 :
#include <iostream>
enum class E;
void foo( const E e );
enum class E
{
V1,
V2
};
void foo( const E e )
{
switch ( e )
{
case E::V1 :
std::cout << "V1"<<std::endl;
break;
case E::V2 :
std::cout << "V2"<<std::endl;
break;
default:
;
}
}
int main()
{
foo( E::V1);
foo( E::V2);
}
To build :
g++ gy.cpp -Wall -Wextra -pedantic -std=c++0x -O3
Is the above standard compliant, or is it using an extension?
When you use -features=extensions, the compiler allows the forward declaration of enum types and variables. In addition, the compiler allows the declaration of a variable with an incomplete enum type.
"Plain" enums and enum class objects both are of integral type, so the decision of passing by const reference or by value is just the same as if you did for other arguments of integral type.
A forward declaration is much faster to parse than a whole header file that itself may include even more header files. Also, if you change something in the header file for class B, everything including that header will have to be recompiled.
If only your class members use the enum it is preferable to declare the enum inside the class. It is more intutive for users of the class, it helps the user to know that the enum will only be used by the class.
A declared enum, even if you don't specify the enumerators (what the standard calls an opaque-enum-declaration) is a complete type, so it can be used everywhere.
For completeness, here's a quote from paragraph 3 of §7.2:
An opaque-enum-declaration is either a redeclaration of an enumeration in the current scope or a declaration of a new enumeration. [Note: An enumeration declared by an opaque-enum-declaration has fixed underlying type and is a complete type. The list of enumerators can be provided in a later redeclaration with an enum-specifier. —end note ]
And the grammar for opaque-enum-declaration, from paragraph one of the same §7.2:
opaque-enum-declaration:
enum-key attribute-specifier-seqopt identifier enum-baseopt
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With