This is for the C preprocessor experts:
How can I declare an enum with a list of some identifiers and later during the switch-statement check if an identifier was included in the list?
Example of what I need:
typedef enum { e1, e2, e3, e4, e5, e6 } e;
e x;
switch (x) {
#if DECLARED_IN_ENUM (e1)
case e1 : ...
#endif
/* etc. */
}
I thought of using a Boost sequence and expanding it into a comma separated list in the enum, but how can I check later if the sequence contains a certain token?
EDIT: What I was able to do with Boost is:
#define e1 e1
#define e2 e2
#define e3 e3
#define e4 e4
#define e5 e5
#define e6 e6
#define E (e1)(e2)(e3)(e4)(e5)(e6)
typedef enum { BOOST_PP_SEQ_ENUM(E) } e;
e x;
switch (x) {
#if defined (e1)
case e1 : ...
#endif
/* etc. */
}
That is not very beautiful, and I would prefer something like:
#define E (e1)(e2)(e3)(e4)(e5)(e6)
typedef enum { BOOST_PP_SEQ_ENUM(E) } e;
e x;
switch (x) {
#if BOOST_PP_SEQ_CONTAINS (e1,E)
case e1 : ...
#endif
/* etc. */
}
but how could BOOST_PP_SEQ_CONTAINS be implemented?
I don’t think
BOOST_PP_SEQ_CONTAINScan be implemented. It would require you to be able to compare two sequences of preprocessing tokens, which you can’t do.However, if you rearrange your logic a bit, you can get something closer to what you want. First, we need a couple of helper macros for use with
BOOST_PP_SEQ_FOR_EACH:We can define the list of enumerators and the enumeration just as you have in the original question:
As you can see, I’ve left Friday off of the list because no one actually does work on Friday. Let’s consider as an example a function that returns some text describing the day of the week.
Instead of testing whether an enumerator was included in the list, we define the cases for each of the values using macros:
We then generate the correct case statements for the list by using the
WORKDAY_ENUMERATORSand concatenating the enumerators with theWORKDAY_CASE_prefix:If a day was not included in the
WORKDAY_ENUMERATORSlist, no case will be generated for it.Because we should be polite when we use the preprocessor, we then undefine the macros we used:
I think this is kind of ugly, but it’s one way to get almost the results you are seeking.