kwjsksai
kwjsksai

Reputation: 347

macro inside enum c++

I need to write functions like this:

void foo()
{
    //some details
}
enum fun_names
{
    fun_name_foo,
};

So I made 2 macros:

#define MAKE_FUN(fun) void fun(){}
#define ADD_FUN(fun) fun_name_##fun,

Then use them like this:

MAKE_FUN(foo)
MAKE_FUN(bar)
enum fun_names
{
    ADD_FUN(foo)
    ADD_FUN(bar)
};

But as you can see, I'm repeating 2 macros with exactly same arguments. Is it possible to make one single macro like this?

CREATE_FUN(foo)
CREATE_FUN(bar)

This saves lines of codes and is less error-prone.

Upvotes: 1

Views: 712

Answers (1)

A possible trick might be to have a macro taking a macro name as argument

#define DO_ENUM(Mac) \
  Mac(foo) \
  Mac(bar)

then

#define DECLARE_ENUM(X) X,
enum fun_names {
  Nothing,
  DO_ENUM(DECLARE_ENUM)
};
#undef DECLARE_ENUM

and to declare the functions:

#define DECLARE_FUN(X) void myfun_##X(void);
DO_ENUM(DECLARE_FUN)
#undef DECLARE_FUN

and so on.

Another way might be to generate some specialized header files, e.g. using some awk script, from another file containing the list of functions etc..

Upvotes: 2

Related Questions