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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With