你不能forward declare an enum in C++ , 但你可以在 C 中。
对于使用一些 C++ 代码的 C 代码库,有没有一种方法可以在 C 中使用前向声明的枚举,当在 C++ 中使用该 header 时(在 extern "C"中)不会导致错误{..}
block )?
例子:
extern "C" {
enum MyEnum;
}
int main() { return 0; }
GCC 给出错误:
error: use of enum ‘MyEnum’ without previous declaration
enum MyEnum;
^~~~~~
Clang 也失败了:
error: ISO C++ forbids forward references to 'enum' types
enum MyEnum;
为了提供一些上下文,这是一个主要是 C 代码库,其中一个小型 C++ 模块恰好包含 C 代码的 header 。我可以做一些 hack 让 C++ 忽略枚举,但我想知道在这种情况下 C++ 是否可以使用 C header 。
更新:官方 C 规范不支持这一点。然而,这似乎是一些最广泛使用的编译器中的事实标准:GCC , Clang , 和 Microsoft Visual C++ .
最佳答案
从 C++11 开始,您可以在 C++ 中前向声明枚举。它被称为“不透明声明”而不是“前向声明”,因为从技术上讲它会产生一些不同的效果:枚举的大小在其不透明声明之后是已知的,而对于前向声明的类型则不是这种情况。
但是,从日常的角度来看,它的想法是一样的:您可以只声明您的枚举并在代码中进一步使用它。 From cppreference :
enum-key attr(optional) nested-name-specifier(optional) identifier enum-base(optional) ;(2) (since C++11)
2) Opaque enum declaration: defines the enumeration type but not its enumerators: after this declaration, the type is a complete type and its size is known. Note: an explicit specialization declaration of a scoped enumeration member of a class template is the only case where nested-name-specifier appears before identifier (since C++14)
关于c++ - 在 C++ 代码中使用的 C header 中转发声明枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45852169/