簡體   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