Hacker News new | ask | show | jobs
by elteto 452 days ago
_This_ is the best pattern for X macros, without any of that noise of undef'ing anything.

My approach is to wrap the list elements with two macros: an inner transformation one and an outer delimiter, like so:

    #define AN_X_LIST(X, DELIM)   \
       DELIM(X(int,         foo)) \
       DELIM(X(int,         bar)) \
             X(std::string, baz)
Then you can compose different pieces of code for different contexts by just swapping out the delimiter. A very contrived example:

    #define SEMICOLON(x) x;
    #define COMMA(x) x,
    
    #define DECLARE(type, var) type var
    #define INIT(type, var) var{}

    struct s {
      AN_X_LIST(DECLARE, SEMICOLON);
      
      s() AN_X_LIST(INIT, COMMA) {}
    };