繁体   English   中英

C++11 Enum forward 导致“底层类型不匹配”

[英]C++11 Enum forward causes “underlying type mismatch”

我在 C++11 中工作,包括一个在 C++03 中实现的 h 文件。 在我包含的 h 文件中,定义了一个枚举Foo 我想在code.h声明一个转发给它并在code.cpp使用它:

标题.h:

enum Foo {A=1};

代码.h:

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

代码.cpp:

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

这是我编译时得到的错误(测试了 g++ 4.8.5 和 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;

如果我将 header.h 更改为:

enum Foo : int {A=1};

但我不拥有那个标题,也不能改变它。 从表面上看错误,听起来我只需要知道 g++ 对没有指定底层类型的枚举使用什么类型,然后在我的转发中使用该类型。

即使这个简单的例子也不起作用

#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";
}

似乎没有任何方法可以做到这一点,即使您指定编译器为您的 C++03 样式enum选择的完全相同的基础类型

示例:编译以下代码...

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

...在 Coliru 上,通过c++filt进行 demangling将使用g++clang++打印"unsigned int"

即使您将unsigned int指定为Foo前向声明的显式基础类型两个编译器也会抱怨

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;
     ^

这是因为前向声明和“真实” enum声明都需要具有相同的显式基础类型,即使您设法“猜测”编译器会为您选择什么。


tl;dr :如果前向声明和实际声明具有相同的明确指定的基础类型,则只能前向声明enum

如果在前向声明中为其提供固定的基础类型,则只能前向声明枚举。 此外,枚举的定义必须使用相同的固定基础类型。

您的问题是header.h中的 enum 定义没有基础类型,但后面的前向声明有一个。 他们两个必须有一个。

从我今天的 gcc 版本开始,您必须两次定义确切的类型,不仅在前向声明中,而且在定义中

enum Foo : int;

...

enum Foo : int {A=1};

这对我有用,编译器是 gcc 7.3.0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM