简体   繁体   中英

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:

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..

However, the problem we have stumbled upon is how to translate a set of C constants into appropriate strongly-typed enum? 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? 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

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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