How do i cherry pick which values I want from my X-macro?

77 views Asked by At

I have an x-macro like this

#define LIST_OF_REGISTERS_R16 \
    X(0x00, B) \
    X(0x10, D) \
    X(0x20, H) \
    X(0x30, S)

and I define it like so

#define X(id, name) name--;
    LIST_OF_REGISTERS_R16
#undef X

the problem is that in certain cases when I'm defining the macro, I need to sometimes select or deselect certain parts of this list, like I might need only B, D, H(without the S) or I might need B,D,S(without the H). I could define an x-macro for every possible combination but then I'd have 24 X-macros just for certain scenarios which is ugly and wasteful. Any help?

1

There are 1 answers

0
fabian On

You could use use an if statement.

#define LIST_OF_REGISTERS_R16(X) \
    X(0x00, B) \
    X(0x10, D) \
    X(0x20, H) \
    X(0x30, S)

#define X(a, b) if constexpr (#b[0] == 'S') std::cout << a << '\n';

int main()
{
    LIST_OF_REGISTERS_R16(X);
}

however, if you're picking single registers out of the list, you're imho better of defining seperate macros for those.

#define REGISTER_R16_B(X) X(0x00, B)
#define REGISTER_R16_D(X) X(0x10, D)
#define REGISTER_R16_H(X) X(0x20, H)
#define REGISTER_R16_S(X) X(0x30, S)

#define LIST_OF_REGISTERS_R16(X) \
    REGISTER_R16_B(X) \
    REGISTER_R16_D(X) \
    REGISTER_R16_H(X) \
    REGISTER_R16_S(X)

#define X(a, b) std::cout << a << '\n';

int main()
{
    REGISTER_R16_S(X);
}