简体   繁体   English

将ctype宏转换为c ++常量的方法

[英]method to convert ctype macros to c++ constants

I have a c++ library which is defined the MACROS like below, 我有一个c ++库,它定义了如下的MACROS,

/* this is defined is the result header file*/ / *定义为结果头文件* /

#define RESULT_ENUM( prefix, name, value )  prefix ## name = (value)

#define STATE_RESULT_LIST( prefix ) \
RESULT_ENUM( prefix, SUCCESS,                        0 ), \
RESULT_ENUM( prefix, PENDING,                        1 ),

#define COMMON_RESULT_LIST( prefix ) \
RESULT_ENUM( prefix, SUCCESS,                        0 ), \
RESULT_ENUM( prefix, PENDING,                        1 ),

typedef enum
{
  STATE_RESULT_LIST     ( STATE_          ) 
  COMMON_RESULT_LIST    ( CHANNEL_        )
}domain_result;

This is how its used 这是它的用法

int main(int argc, char** argv) {
domain_result res = CHANNEL_SUCCESS;
cout<<STATE_SUCCESS <<endl;
cout<<CHANNEL_PENDING<<endl;
return 0;
}

as everyone suggests that we should not use macros, now I dont want to change the c++ source files, need changes only headerfile. 正如每个人都建议我们不应该使用宏一样,现在我不想更改c ++源文件,只需要更改头文件即可。

So how to convert these in to c++ style enums and static constants.? 那么如何将它们转换为c ++样式的枚举和静态常量呢?

You can use g++ -E to figure out how domain_result gets defined in the end. 您可以使用g++ -E弄清楚如何domain_result定义domain_result

As it turns out, all of that can be replaced by: 事实证明,所有这些都可以替换为:

enum domain_result
{
   STATE_SUCCESS = 0,
   STATE_PENDING = 1,
   CHANNEL_SUCCESS = 0,
   CHANNEL_PENDING = 1,
};

If there is a need to have all the tokens of the enum to have unique values, you can simplify that to: 如果需要使enum所有令牌具有唯一值,则可以将其简化为:

enum domain_result
{
   STATE_SUCCESS, // = 0 by default.
   STATE_PENDING,
   CHANNEL_SUCCESS,
   CHANNEL_PENDING,
};

option 1: 选项1:

enum domain_result : uint8_t
{
    STATE_SUCCESS = 0,
    STATE_PENDING = 1,
    CHANNEL_SUCCESS = 0,
    CHANNEL_PENDING = 1,
};

option 2: 选项2:

const uint8_t STATE_SUCCESS = 0;
const uint8_t STATE_PENDING = 1;
const uint8_t CHANNEL_SUCCESS = 0;
const uint8_t CHANNEL_PENDING = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM