繁体   English   中英

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

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

我们有一个顶级 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();
...

为了方便起见,这个想法是为这个 header 文件提供一个 C++ 包装器:即,它只是将一组常见的函数包装到类中,处理错误的异常,所有这些都很好,Z531704A02607A1646EFCFEEC6

但是,我们偶然发现的问题是如何将一组 C 常量转换为适当的强类型枚举? 和上面一样应该翻译成:

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

手动执行此操作本质上违反了 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?

你可以使用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

我建议将static添加到 C 变体中,以避免在链接多个翻译单元时由于多个定义而出现问题。

暂无
暂无

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

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