In C++, I need to defined a macro. That macro would take as parameter a \"block\" of code.
Can we safely use several lines of code as parameter of a macro fu
16.3/9:
Within the sequence of preprocessing tokens making up an invocation of a function-like macro, new-line is considered a normal white-space character.
So the multi-line macro invocation in general is fine. Of course if DOSOMETHING and DOANOTHERTHING don't introduce braces for scope, then your particular example will redefine k.
Edit:
We can't use functors because we need to have access to the context of the call. We can't use lambda (snif) because we use an old compiler
The usual way is to capture whichever variables you need in the functor, just like a lambda does. The only thing a lambda can do that a functor can't is "capture everything" without having to type it out, but whoever writes the lambda can see what variables they use, so that's just convenience, they could type them all out if they had to. In your example:
struct MyFunctor {
int o;
MyFunctor(int o) : o(o) {}
void operator()() const { // probably not void in practice
int k = AFunction();
k++;
AnotherFunction( k + o );
}
};
template
void DoThings(const F &f) {
DOSOMETHING(f());
DOANOTHERTHING(f());
}
int my_function() {
int o = RandomNumber();
DoBothThings(MyFunctor(o));
}
You can also capture variables by reference (usually using a pointer as the data member rather than a reference, so that the functor can be copy-assigned).
If by "context", you mean for example that the macro argument and/or the macro body might contain a break or goto, and hence needs to be inside the lexical scope of the caller then you can't use a functor or a lambda. For shame ;-)