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.
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::map
s 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With