将 #define 字符* 转换为枚举值

Convert a #define'd char* to enum value

本文关键字:枚举 转换 #define 字符      更新时间:2023-10-16

在我无法编辑的标题中,我有以下定义:

#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 */