C ++ 11 Enum forward causes a "base type mismatch",

I work in C ++ 11 and include the h file implemented in C ++ 03. In the h file, I include the Foo enumeration there. I want to declare it in code.h and use it in code.cpp :

header.h:

 enum Foo {A=1}; 

code.h:

 enum Foo : int; // also tried : unsigned int, long, short, unsigned short, char, unsigned char void bar(Foo foo); 

code.cpp:

 #include header.h void bar(Foo foo) { } 

This is the error I get when compiling (checked g ++ 4.8.5 and g ++ 5.3.1):

 In file included from code.cpp:2:0: header.h:1:6: error: underlying type mismatch in enum 'enum Foo' enum Foo {A=1}; ^ In file included from code.cpp:1:0: code.h:3:12: error: previous definition here enum Foo : int; 

I can fix this error if I change the .h header to:

 enum Foo : int {A=1}; 

But I do not own this title and cannot change it. Accepting an error on the value of the face, it sounds as if I need to know what type g ++ uses for enums that do not indicate a base type, and then use that type in my transition.

Even this simple example does not work :

 #include <iostream> #include <string> #include <type_traits> enum Foo {A=1}; enum Foo : unsigned; // : std::underlying_type<Foo>::type also doesn't work int main() { std::cout << "Hello, world\n"; } 
+8
c ++ gcc c ++ 11 g ++ forward-declaration
source share
2 answers

This doesn't seem to be the case even if you specify the same base type that the compiler chose for your C ++ 03 enum style.

Example: compiling the following code ...

 enum Foo { A=1 }; cout << typeid(std::underlying_type_t<Foo>::type).name(); 

... on Coliru and demangling through c++filt will print "unsigned int" with both g ++ and clang ++ .

Even if you specify unsigned int as the explicit base type of your Foo forward declaration, both compilers will complain .

 enum Foo : unsigned int; void bar(Foo); enum Foo {A=1}; 

 main.cpp:8:6: error: enumeration previously declared with fixed underlying type enum Foo {A=1}; ^ main.cpp:5:6: note: previous declaration is here enum Foo : unsigned int; ^ 

This is because both the forward declaration and the "real" enum must have the same explicit base type, even if you manage to "guess" what the compiler would choose for you.


tl; dr : you can only forward-declare enum if both the forward declaration and the real declaration have the same explicitly specified base type.

+5
source share

You can only forward the enumeration if you give it a fixed base type in the forward declaration. In addition, the enumeration definition must use the same fixed base type.

Your problem is that the definition of your enum in header.h does not have a base type, but there is one thing in the later declaration. They should both have one.

+4
source share

All Articles