9

I know it's better to avoid macros in c++. Use inline functions to replace function-like macros, and constexpr/using to replace const-variable-define macros. But I would like to know if there is one way to replace macro concatenation functionality by some modern c++ techniques.

For example, how to replace the following macros:

#define GETTER_AND_SETTER(name)     \
   inline void Set##name(int value) \
   {                                \
      m_##name = value;             \
   }
   inline int Get##name() const     \
   {                                \
      return m_##name;              \
   }

then in a class, I can do this for a lot of variables, which makes the code more clean.

GETTER_AND_SETTER(Variable1)
GETTER_AND_SETTER(Variable2)
GETTER_AND_SETTER(Variable3)
...

I have checked here and here, but I don't get the answer. So any idea about this?

Edit: The example of getters/setters is just used to show the idea. Please don't focus on them.

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
houghstc
  • 127
  • 7

1 Answers1

14

You can't.

There's no magic that you can perform with variable names at compile-time; C++ simply does not have any reflection capabilities. You may only generate code using the preprocessor to do the magic.

Typical workarounds involve std::maps of "names" to values, but your existing approach seems pretty reasonable to me unless you have a brazillion of the things.

Although, depending on your requirements, you might do better to forget about this "getter"/"setter" nonsense anyway, and just define some logical, semantic member functions for your class. If you're literally just creating a direct accessor and mutator for each member variable then, really, what's the point?

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • One of the points might be to find all places in code which exactly read or exactly write the data member. (You could only find where it's _accessed_ if you just read-write it directly.) This doesn't help with class' own methods though, which can access private data. This also hints that the class would just be an improved POD thing. – Ruslan Aug 11 '16 at 09:35
  • @Ruslan: Perhaps, but if you have more than one or two places of code writing to the same object, then your program is badly written and you don't have enough `const`. So it kind of becomes a moot point. – Lightness Races in Orbit Aug 11 '16 at 09:41
  • Thank you for your answer. It's just an example to show the idea. :) – houghstc Aug 11 '16 at 09:46