map-macro icon indicating copy to clipboard operation
map-macro copied to clipboard

How to map pairs of __VA_ARGS__?

Open jordi-reinsma opened this issue 6 years ago • 1 comments
trafficstars

Is there any way to extend that macro so you can apply it to pairs of arguments? Something like this:

#define DECL_VAR(type,var)\
  type _##var;
#define DECL_GETSET(type,var)\
  type get_##var() const {return _##var;}\
  void set_##var(type val) {_##var = val;}

#define CREATE_CLASS(C, ...)\
  class C {\
    private:\
    MAP_PAIR(DECL_VAR, ODD_VA_ARG, EVEN_VA_ARG)\
    public:\
    MAP_PAIR(DECL_GETSET, ODD_VA_ARG, EVEN_VA_ARG)\
  };

CREATE_CLASS(Person, const char*, name, int, age, float, height)
// or maybe
CREATE_CLASS(Person, (const char*, name), (int, age), (float, height))

jordi-reinsma avatar Oct 08 '19 03:10 jordi-reinsma

I achieved this in my own code (where I wanted the comma-inserting list variant) with the following extra definitions:

#define MAP_PAIR_LIST0(f, x, y, peek, ...) f(x, y) MAP_LIST_NEXT(peek, MAP_PAIR_LIST1)(f, peek, __VA_ARGS__)
#define MAP_PAIR_LIST1(f, x, y, peek, ...) f(x, y) MAP_LIST_NEXT(peek, MAP_PAIR_LIST0)(f, peek, __VA_ARGS__)

/// Applies the function macro `f` to each pair of the remaining parameters and
/// inserts commas between the results.
#define MAP_PAIR_LIST(f, ...) EVAL(MAP_PAIR_LIST1(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))

str4d avatar Dec 24 '20 14:12 str4d