Pass block of statements as arguement to the function call

Viewed 55

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?

1 Answers

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);
}
Related