Passing code as an argument (C ++)

How do I go about passing a code block to a function in C ++. In C #, I can do something like this:

void Example(Action action)
{
    action();
}

Example(() => {
    //do something
});

All help and advice is appreciated.

+4
source share
4 answers

Here is a simple example to start with ...

void Example(void (*x)(void))
{
    x();
}

and the challenge will be ...

Example([] { cout << "do something\n"; });

This is very similar to your C # example. And there are better, more universal ways to do this, as the comments show. If you wanted to return a value and take a parameter, you could do something like this ...

int Example2(int (*y)(int i), int p)
{
    return y(p);
}
// ...
auto ret = Example2([](int p) -> int { cout << p << "\n"; return p; }, 2);

It will be similar to the C # version as follows

int Example2(Func<int,int> y, int p)
{
    return y(p);
}
// ...
var ret = Example2((p) => { /*etc*/ return p; }, 2);
+4
source

C ++ 11 equivalent:

void Example(const std::function<void()>& action)
{
    // always good to make sure that action has a valid target
    if(action != nullptr)
        action();
}

Example([] {
    //do something
});
+3
source

std::function<Result(Param1, Param2, ...)> , :

  • . - C ++ 98.

    void example(void (*action)()) {
        action();
    }
    
    void example_action() {
        std::cout << "action\n";
    }
    
    example(example_action);
    
  • , . Lambdas ++ 11 .

    void example(void (*action)()) {
        action();
    }
    
    example([]() {
        std::cout << "action\n";
    });
    
  • ( operator()) , ( "" ).

    template<class F>
    void example(F action) {
        action();
    }
    
    int x = 4;
    example([x]() {
        std::cout << "action (" << x << ")\n";
    });
    
    struct example_action {
        void operator()() {
            std::cout << "action\n";
        }
    };
    
    example(example_action());
    
  • std::function , .

    void example(std::function<void()> action) {
        action();
    }
    
    int x = 4;
    example([x]() {
        std::cout << "action (" << x << ")\n";
    });
    
  • .

    template<void (*action)()>
    void example() {
        action();
    }
    
    example<example_action>();
    

, # 3 example , , , . # 4 , example . # 5 , , inlining.

+3

std::function<void()> Action ++ -:

void Example(std::function<void()> action)
{
    action();
}

Example([]() {
    //do something
});

std::function, @Les , lambdas, .

+1

Source: https://habr.com/ru/post/1611685/


All Articles