Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing code as an argument (C++)

Tags:

c++

How would 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 tips are greatly appreciated.

like image 943
user3289547 Avatar asked Dec 19 '22 23:12

user3289547


1 Answers

Here is a simple example to get started with...

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

and the call would be...

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

This is very similar to your C# example. And there are better, more versatile ways of doing this as the comments suggest. If you had 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);

This would 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);
like image 158
Les Avatar answered Dec 21 '22 12:12

Les