www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Enum template for cpp binding

reply novice3 <sorryno em.ail> writes:
Hello.
I want make binding for some CPP api.
I have .h file with enums like:

///////////
typedef enum {
     SOMEAPI_PHASE_A = 91,
     SOMEAPI_PHASE_B = 92,
     SOMEAPI_PHASE_C = 93
} someapiPhase;
///////////

It used later in .cpp like:
func(SOMEAPI_PHASE_A);


I want .d file like this:

///////////
enum SOMEAPI_PHASE {
     A = 91,
     B = 92,
     C = 93
}
alias SOMEAPI_PHASE_A = SOMEAPI_PHASE.A;  // for using like 
anonymous enum like C++
alias SOMEAPI_PHASE_B = SOMEAPI_PHASE.B;
alias SOMEAPI_PHASE_C = SOMEAPI_PHASE.C;
alias SomeapiPhase = SOMEAPI_PHASE;  // for using type in func 
declarations
///////////

This is reduced example.
I am sorry for this type of question,
but could please anybody show me template for this boring coding?
Is this possible to avoid this manual coding?
Show me direction or examples please.

Thanks.
Feb 15 2021
parent reply Paul Backus <snarwin gmail.com> writes:
On Monday, 15 February 2021 at 12:37:14 UTC, novice3 wrote:
 This is reduced example.
 I am sorry for this type of question,
 but could please anybody show me template for this boring 
 coding?
 Is this possible to avoid this manual coding?
 Show me direction or examples please.
This will do most of it: mixin template declareAnonymous(E, string sep = "_") if (is(E == enum)) { static foreach (memberName; __traits(allMembers, E)) { mixin( "alias ", __traits(identifier, E), sep, memberName, " = __traits(getMember, E, memberName);" ); } } Usage: enum MY_ENUM { A, B, C } mixin declareAnonymous!MY_ENUM; static assert(MY_ENUM_A == MY_ENUM.A); static assert(MY_ENUM_B == MY_ENUM.B); static assert(MY_ENUM_C == MY_ENUM.C);
Feb 15 2021
parent novice3 <sorryno em.ail> writes:
On Monday, 15 February 2021 at 14:03:26 UTC, Paul Backus wrote:
 This will do most of it:
Thank you Paul!
Feb 15 2021