1

Consider the following example:

func(cond, block_A, block_B) {
    if(cond) {
        block_A; // Run all the statements in the block A
    } else {
        block_B; // Run all the statements in the block B
    }
}

int main() {
    block_A = {
        y = 1;
        std::cout << (y);
        // statement continues ...
    }
    block_B = {
        z = 1;
        std::cout << (z);
        // statement continues ...
    }

    func(true, block_A, block_C);
}

Is there any way to pass a block of statements as an argument to the function call?

  • This is not how C++ works. `block_A` doesn't have any type. Refer to a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). You can put those blocks in a function and then pass a pointer to that function. – Jason Sep 13 '22 at 09:21
  • You can pass them as `std::function` which will invoke whatever sequence you want – Sergey Kolesnik Sep 13 '22 at 09:21
  • 5
    How about [*lambda* expressions](https://en.cppreference.com/w/cpp/language/lambda)? – Some programmer dude Sep 13 '22 at 09:25

1 Answers1

6

You can pass callables to func and use lambda expressions:

#include <iostream>

template <typename F,typename G>
void func(bool cond, F a, G b) {
    if(cond) {
        a(); // Run all the statements in the block A
    } else {
        b(); // Run all the statements in the block B
    }
}

int main() {
    auto block_A = [](){
        int y = 1;
        std::cout << y;
    };
    auto block_B = [](){
        int z = 1;
        std::cout << z;
    };

    func(true, block_A, block_B);
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • That works, thank you. But I have a doubt, how do I initialize the variable `y` in the `main()` scope, use the `y` value and store some other value in `y` inside the `block_A` scope and retrieve the value in the `main()` scope. – Addiction99 Sep 14 '22 at 03:46
  • @Addiction99 read about lambdas and captures – 463035818_is_not_an_ai Sep 14 '22 at 06:52
  • @Addiction99 fwiw, I rejected your edit because it doesnt match what you ask for in the question. In the question you ask for executing the whole block inside `func`. In your edit you moved part of the block out, this wasnt asked for in the question. When I have time I might add what you suggested as edit as additional information. – 463035818_is_not_an_ai Sep 14 '22 at 15:48
  • The changes which I added to the edit were the ones that I was looking for. Please add the addition information. That would be very helpful.Thank you – Addiction99 Sep 14 '22 at 15:54
  • @Addiction99 sorry, but I dont understand. Is the answer not answering your question? It does execute the two blocks you named `block_A` and `block_B` in `func` – 463035818_is_not_an_ai Sep 14 '22 at 15:55