9

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?

BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • Your code would work equally well with a forward-declared class: `struct A; void foo(A); struct A {}; void foo(A) {}` is valid code. See [When to use forward declaration](http://stackoverflow.com/q/553682/20984). – Luc Touraille Jan 18 '12 at 16:29
  • What you could have tried is *define* (and not *declare*) `foo` before defining `E`. – Luc Touraille Jan 18 '12 at 16:30
  • @LucTouraille The 1st link tells it all (thanks). For the 2nd thing, I know that I would get `error: 'V1' is not a member of 'E'` errors with the reason, but this would compile fine : `void foo( const E e ) { std::cout << (int)e< – BЈовић Jan 18 '12 at 16:45

1 Answers1

11

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;

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • 1
    And that's why opaque-enums always have a fixed underlying type (`int` if not explicitly set): because this way it size is fixed without depending on the values of the constants. – rodrigo Jan 18 '12 at 14:21