简体   繁体   English

自动将一组 C 常量转换为 C++ 强类型枚举

[英]Automatically translate a set of C constants to C++ strongly typed enum

We have a top-level C library header file which contains a set of constants (and also C functions or course), eg:我们有一个顶级 C 库 header 文件,其中包含一组常量(以及 C 函数或课程),例如:

const int32_t Sample_FooFoo = 1;
const int32_t Sample_FooBar = 2;
const int32_t Sample_BarFoo = 3;
const int32_t Sample_BarBar = 4;

int API_Function_BarbarbarFooFoo_1();
int API_Function_BarbarbarFooFoo_2();
...

The idea is to provide also a C++ wrapper for this header file for convenience: ie, it just wraps a common group of functions into classes, exceptions to handle errors, all nice and shiny..为了方便起见,这个想法是为这个 header 文件提供一个 C++ 包装器:即,它只是将一组常见的函数包装到类中,处理错误的异常,所有这些都很好,Z531704A02607A1646EFCFEEC6

However, the problem we have stumbled upon is how to translate a set of C constants into appropriate strongly-typed enum?但是,我们偶然发现的问题是如何将一组 C 常量转换为适当的强类型枚举? Like the one above should be translated into:和上面一样应该翻译成:

enum class Sample : int32_t 
{
    FooFoo = 1,
    FooBar = 2,
    ...
};

Doing this manually essentially violates DRY paradigm which is not so nice and shiny anymore.. Perhaps there is some automatic way to do this?手动执行此操作本质上违反了 DRY 范式,它不太好,shiny 不再存在了。也许有一些自动的方法可以做到这一点? For instance, by writing a python script which would parse C header file and translate each group of constants (maybe propertly annotated) into a corresponding C++ enum? For instance, by writing a python script which would parse C header file and translate each group of constants (maybe propertly annotated) into a corresponding C++ enum?

You could use XMacro你可以使用XMacro

#define SAMPLE_ENUMS \
  X(FooFoo, 1) \
  X(FooBar, 2) \
  X(BarFoo, 3) \
  X(BarBar, 4)

#if __cplusplus

enum class Sample : int32_t 
{
  #define X(NAME,VAL) NAME = VAL,
  SAMPLE_ENUMS
  #undef X
};

#else

#define X(NAME,VAL) const int32_t Sample_## NAME = VAL;
SAMPLE_ENUMS
#undef X

#endif

I suggest adding static to C variant to avoid problem when linking multiple translation units due to multiple definitions.我建议将static添加到 C 变体中,以避免在链接多个翻译单元时由于多个定义而出现问题。

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

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