fork download
  1. // Create class members and methods with X-Macros
  2. // Klaus Warnke
  3.  
  4. #include <string>
  5. #include <tuple>
  6. #include <iostream>
  7. #include <cassert>
  8.  
  9. #define MEMBER_TBL \
  10.   /*type ,name ,default*/ \
  11.   X(int ,_(i) ,42 ) \
  12.   X(float ,_(f) ,3.14 ) \
  13.   X(std::string , t ,"Hello") \
  14.  
  15. struct Foo
  16. {
  17. #define _(x) x
  18. #define X(type, name, default) type name{default};
  19. MEMBER_TBL
  20. #undef X
  21. #undef _
  22.  
  23. bool operator==(Foo const& other) const {
  24. return std::tie(
  25. #define _(x) x,
  26. #define X(type, name, default) this->name
  27. MEMBER_TBL
  28. #undef X
  29. ) == std::tie(
  30. #define X(type, name, default) other.name
  31. MEMBER_TBL
  32. #undef X
  33. #undef _
  34. );
  35. }
  36.  
  37. void print() const {
  38. #define STR(x) #x
  39. #define _(x) x
  40. #define X(type, name, default) \
  41.   std::cout << \
  42.   STR(name) << ": " << name << " ";
  43. MEMBER_TBL
  44. #undef X
  45. #undef _
  46. #undef STR
  47. std::cout << std::endl;
  48. }
  49. };
  50.  
  51. #undef _
  52. #undef MEMBER_TBL
  53.  
  54. int main(void)
  55. {
  56. Foo foo{}, bar{};
  57.  
  58. assert(foo == bar);
  59. bar.t = "bye";
  60. assert(! (foo == bar));
  61.  
  62. foo.print(); // i: 42 f: 3.14 t: Hello
  63. bar.print(); // i: 42 f: 3.14 t: bye
  64.  
  65. return 0;
  66. }
  67.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
i: 42 f: 3.14 t: Hello 
i: 42 f: 3.14 t: bye