What I am seeking is a way to create a function that accepts a block of code as argument.
I've seen this in boost's for-each loop But I can't find a way to do it myself
I've searched but didn't find anything(probably my terminology was wrong)
An example of what I want:
int main() {
DO_SOMETHING_FUNC(arg1, arg2, arg3) {
//Block
}
}
CodePudding user response:
This specific syntax can only be achieved with a macro.
If possible, you should prefer a macro-less approach, i.e. passing a lambda to the function:
do_something_func(foo, bar, [&]
{
});
The last parameter of my_for_each
either needs to have a templated type:
template <typename F> void my_for_each(/*blah, blah, */ F func)
Or it can be std::function
.
To get this exact syntax (without ;
after }
), the macro needs to end with something like for (...)
or if (...)
(depending on how you want to use the code block), so the following braces become the body of this control statement.
This might not be flexible enough in some cases, e.g. if you're writing a scope guard.
If you change the syntax to have ;
after }
, things become easier. You can make your macro DO_SOMETHING_FUNC(x, y)
expand to myHelper(x, y) ->* [&]
, where myHelper()
returns an object with an overloaded binary operator (used ->*
here, because it has the highest available priority). The braces following the macro become the lambda body, and the overloaded operator receives said lambda as the second argument.