I have a bunch of classes such as the following,
class SomeClass : public Function{
public:
ref call(ref args){
// do & return stuff
}
int getType(){return TYPE;}
ref toString(){ return "SomeClass";}
};
I got like 50 of these and the only thing that is different is the body of the call function. Is it possible to have a macro that will take a name and a body and replace "SomeClass" with name and insert body into call function?
Sure. Expanding the body of the call member function is a bit easier if you have a compiler that supports variadic macros. While I've used Boost.Preprocessor's stringize macro, it is trivial to write your own.
#define DEFINE_CLASS(name, parenthesized_call_body) \
class name : public Function { \
ref call (ref args) { \
DEFINE_CLASS_CALL_BODY parenthesized_call_body \
} \
int getType() { return TYPE; } \
const char* toString() { return BOOST_PP_STRINGIZE(name); } \
};
#define DEFINE_CLASS_CALL_BODY(...) __VA_ARGS__
Used as:
DEFINE_CLASS(SomeClass, (return ref()))
The call body needs to be parenthesized so that any commas present in the body are not treated as macro argument separators. Alternatively, you could just declare the call function in the class definition and then define that function separately.
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