将 #define 字符* 转换为枚举值
Convert a #define'd char* to enum value
在我无法编辑的标题中,我有以下定义:
#define ENUM_SOMETHING_A "A"
#define ENUM_SOMETHING_B "B"
#define ENUM_SOMETHING_C "C"
我想将它们包装在一个枚举中,类似于:
enum Something {
A = ENUM_SOMETHING_A,
B = ENUM_SOMETHING_B,
C = ENUM_SOMETHING_C
};
其中 Something::A 是 ENUM_SOMETHING_A 的十进制 ASCII 值,依此类推。
我已经尝试了几种方法,但我不知道该怎么做。是否可能,如果可能,我该如何完成?同样,#defines 无法更改。
我尝试了铸造,我尝试了ENUM_SOMETHING_A[0],但都没有奏效。另外 - 这不是 C++0x。
枚举值不能是字符串,因此在这里使用枚举并不合适,除非您想添加一种额外的机制来将枚举值映射到它们的字符串对应项。 但是,您可以执行以下操作:
// Header
typedef char const * Something_value;
namespace Something
{
Something_value const A;
Something_value const B;
Something_value const C;
}
// Implementation
namespace Something
{
Something_value const A = ENUM_SOMETHING_A;
Something_value const B = ENUM_SOMETHING_B;
Something_value const C = ENUM_SOMETHING_C;
}
你不能在语言中执行此操作。 但是,您可以编写一个 shell 脚本,从无法编辑的标头生成所需的枚举。 它看起来像这样:
#! /bin/sh
# usage: define2enum input output
set -e
exec > "$2"
echo 'enum Something {'
sed -ne 's/^#define ENUM_SOMETHING_([A-Za-z0-9][A-Za-z0-9]*) "(.)"$/ 1 = '''2''',/p' < "$1"
echo '};'
你不能
。 必须使用整数常量定义enum
。 根据定义,char*
不是整数常量。
你能做的最好的事情就是将常量映射到等效的char
值(你可以根据自己的喜好进行算术调整):
#define MY_ENUM_SOMETHING_A (ENUM_SOMETHING_A[0]) /* 65 */
#define MY_ENUM_SOMETHING_B (ENUM_SOMETHING_B[0]) /* 66 */
#define MY_ENUM_SOMETHING_C (ENUM_SOMETHING_C[0]) /* 67 */
相关文章:
- 错误:从"int"到枚举c++的转换无效
- 将作用域枚举转换为基础类型
- 枚举类的 C 样式强制转换到基础类型 char 的引用
- 用于 boost::p roperty_tree 的通用枚举转换器
- 在编译时将强类型枚举器转换为其基础类型?
- SWIG-将C++枚举转换为Python枚举
- 如何将C++代码中的枚举转换为 C
- 将枚举转换为_variant_t C++
- 将枚举转换为值的正确方法
- 通用 int -> 可以使用模板进行枚举转换吗?
- 在 C++ 中通过 int 将枚举转换为枚举
- 将枚举转换为字符串
- 超出范围的枚举转换能否生成基础类型之外的值
- 将已有的枚举转换为字符串
- 如何自动将强类型枚举转换为整型
- 如何将c++枚举转换为ctypes ?结构使用Python 2.7.2
- 将C++枚举转换为python int
- C++11 将枚举转换为整数
- 有没有一种简单的方法可以将C++枚举转换为字符串
- 应该如何将C位标志枚举转换为C++