I want to define a macro within another macro, in order to save me some repetetive writing.
Currently I have to write this:
MyClass : public Base<MyClass> {
Value<std::string> testString = value<std::string>(&MyClass::testString, "something");
// many more values like this
}
And I want to write something like this, in order to reduce the cluttery of the above:
BASE(MyClass) {
VALUE(std::string, testString, "something");
}
My solution would have been to define two function style macros and BASE
and VALUE
and within BASE
define another constant named __CURRENT_CLASS
that will be used for all calls of VALUE. But how do I define this constant within the BASE
macro?
Not exactly the same syntax, but you can define a type alias to give the class name something that's always the same.
It's not possible to define a macro inside a macro. An alternative, used when the macros are very complex, is to #define
some parameters that will be used and then #include
a header file containing macro definitions. Then the parameters can be redefined and header included again.
#include <string>
template <typename T> class Base {};
template <typename T> struct Value {};
template <typename T, typename Container>
Value<T> value(Value<T> Container::*, const T&);
#define BASE(name) \
class name: public Base<name> { \
using ThisClass = name;
#define ENDBASE(name) }
#define VALUE(name, type, init) \
Value<type> name = value<type>(&ThisClass::name, init)
BASE(MyClass)
VALUE(testString, std::string, "something");
ENDBASE(MyClass);