【发布时间】:2017-08-03 15:48:07
【问题描述】:
我正在使用 C++11 并包含一个用 C++03 实现的 h 文件。在我包含的 h 文件中,定义了一个枚举 Foo。我想在code.h 中声明一个转发并在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) { }
这是我编译时遇到的错误(测试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++ 用于未指定底层类型的枚举的类型,然后在我的转发中使用该类型。
Even this simple example doesn't 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";
}
【问题讨论】:
-
好吧,C++ 标准明确禁止这样做(前向声明枚举需要固定的底层类型)。也许另一种解决方案是可能的,比如将枚举包装在一个结构中?
-
阅读 stackoverflow.com/questions/71416/…,我认为在 C++11 中是可能的。
-
从 C++11 开始,您可以前向声明一个枚举,但这需要修复底层类型(“指定一个枚举基数”),并为每个声明重复相同的底层类型(前向-声明或实际声明)。因此,如果您不能将基础类型添加到外部标头,那么您不能(不允许)前向声明此枚举。
-
std::underlying_type告诉您enum的基础类型。它对您的枚举有什么影响? -
@Yakk,
unsigned。但是,如果我这样做enum Foo : unsigned- 我会收到上面的错误。
标签: c++ c++11 gcc g++ forward-declaration