I’m trying to utilize the preprocessor in C++ in a way which would ease my development progress enormously! I have a pretty simple issue, I work with a C API library whilst I use regular C++ classes. This library is based on callbacks/events, which I only can supply functions (not methods) to. Because of this I have a repetitive pattern of declaring a static and non-static function for each event:
public: // Here is the static method which is required
static inline Vector StaticEventClickLeft(Vector vec) { return globalClass->EventClickLeft(vec); }
private: // And here is the method (i.e non-static)
Vector EventClickLeft(Vector vec);
I want to create a macro which defines both these in a single line. It would decrease the size of my header by ten times at least! Here is my closest attempt (but far from enough):
#define DECL_EVENT(func, ret, ...) \
public: static inline ret S ## Event ## func(__VA_ARGS__) { return globalClass->Event ## func(__VA_ARGS__); } \
private: ret Event ## func(__VA_ARGS__);
If I use this macro like this DECL_EVENT(ClickLeft, Vector, Vector vec). This will be the output:
public: static inline Vector SEventClickLeft(Vector vec) { return globalClass->EventClickLeft(Vector vec); }
private: Vector EventClickLeft(Vector vec);
You can clearly see the problem. The static function calls the method and supplies the type of the argument as well as the name. Since the type is specified, it results in a compiler error; include/plugin.h:95:2: error: expected primary-expression before ‘TOKEN’ token.
So how can I solve this? There must be some solution, and I’m sure some macro expert can offer some help!
First, place parenthesis around your types, so the preprocessor can parse it. So you will call DECL_EVENT like this:
Here are some macros that will retrieve the type and strip off the type(you will want to namespace them, I am leaving off the namespace just for demonstration):
These macros work like this. When you write
STRIP((Vector) vec)it will expand tovec. And when you writePAIR((Vector) vec)it will expand toVector vec. Now next, you will want to do is to apply these macros to each argument that is passed in, so here is a simpleAPPLYmacro that will let you do that for up to 8 arguments:Now heres how you can write your
DECL_EVENTmacro:Note: This probably won’t work in MSVC, since they have a buggy preprocessor(although there are workarounds).