如何将指针值转换为枚举?
How to cast pointer value to enumeration?
我有以下内容:
enum TestEnum { One=1, Two, Three };
int main()
{
char const* data = reinterpret_cast<char const*>(One);
TestEnum e = reinterpret_cast<TestEnum>(data);
}
Clang 编译失败:
main.cpp:11:18: error: reinterpret_cast from 'const char *' to 'TestEnum' is not allowed
TestEnum e = reinterpret_cast<TestEnum>(data);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
为什么 reinterpret_cast
在这种情况下不起作用?我试过删除 const
但这没有什么区别。我在 C++11 规范中没有看到任何说明枚举的特殊行为的内容。
从 5.2.10/4 开始:"A pointer can be explicitly converted to any integral type large enough to hold it."枚举不是整数类型。
(第5段允许反向:"A value of integral type or enumeration type can be explicitly converted to a pointer.")
我有以下内容:
enum TestEnum { One=1, Two, Three };
int main()
{
char const* data = reinterpret_cast<char const*>(One);
TestEnum e = reinterpret_cast<TestEnum>(data);
}
Clang 编译失败:
main.cpp:11:18: error: reinterpret_cast from 'const char *' to 'TestEnum' is not allowed
TestEnum e = reinterpret_cast<TestEnum>(data);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
为什么 reinterpret_cast
在这种情况下不起作用?我试过删除 const
但这没有什么区别。我在 C++11 规范中没有看到任何说明枚举的特殊行为的内容。
从 5.2.10/4 开始:"A pointer can be explicitly converted to any integral type large enough to hold it."枚举不是整数类型。
(第5段允许反向:"A value of integral type or enumeration type can be explicitly converted to a pointer.")