Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace c++ macro's concatenation by modern c++ techniques

Tags:

c++

c++11

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.

like image 660
houghstc Avatar asked Aug 11 '16 09:08

houghstc


1 Answers

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?

like image 53
Lightness Races in Orbit Avatar answered Oct 04 '22 01:10

Lightness Races in Orbit