-3

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
    }
}
Vbrawl
  • 77
  • 4
  • 1
    Things and terms to research: Function pointers, templates, `std::function` and lambdas. – Some programmer dude Sep 26 '21 at 07:19
  • 1
    Look up "c++ lambdas". – n. m. could be an AI Sep 26 '21 at 07:19
  • Does this answer your question? [Is it possible to create a function dynamically, during runtime in C++?](https://stackoverflow.com/questions/11016078/is-it-possible-to-create-a-function-dynamically-during-runtime-in-c) – MoonLight Sep 26 '21 at 07:20
  • @MoonLight it doesn't help, what i am seeking is a way to get the body as argument (to like call it inside of my function) – Vbrawl Sep 26 '21 at 07:25
  • @n. 1.8e9-where's-my-share m. I don't think lambdas and functions are what I need here because I want to be able to use it without declaring it first (or declaring inside of the arg list) – Vbrawl Sep 26 '21 at 07:29
  • 1
    The lambda can be defined in the argument list of the function you call. And that function can in turn call the lambda at any time (it isn't called immediately). – Some programmer dude Sep 26 '21 at 07:32
  • _what i am seeking is a way to get the body as argument (to like call it inside of my function)_ This is precisely what can be achieved with lambdas... :-) Of course, you have to care about to give your function a "callbable" as argument. (The answer suggest multiple options.) – Scheff's Cat Sep 26 '21 at 07:55

1 Answers1

2

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.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207