-2

can somebody help me find a solution? I want to know whether there is a C++ equivalent for the following C# code:

// C# Code here

private void Execute(Action action)
{
    action();
}

Which can be called like this:

this.Execute( () => { this.DoA(); this.DoB(); } );

Now what I have come up with is to wrap the calls to this.DoA(); and this.DoB(); in another method and pass that as a function pointer:

// C++ Code here

void Execute(void (*f))
{
    (*f);
}

and

void DoBoth()
{
    DoA();
    DoB();
}

so then it can be called like this, which also works:

Execute(DoBoth);

But I am looking for a way without having to declare a method DoBoth. I know I could just use multiple parameters, but I dont want to restrict the number of the parameters and therefore I was hoping for a way like in C#.

Any help is gladly appreciated.

Rakete1111
  • 42,521
  • 11
  • 108
  • 141
Thomas Flinkow
  • 3,956
  • 5
  • 23
  • 52

1 Answers1

1

The term you're looking for is "lambda expression". Basically, it's a anonymous function.

I'll be honest, I have zero experience with C++ lambda.

They've been introduced in C++ 11 it would seem, and take the following form:

[]() {}

Instead of making plagiarism, I'll redirect you to this stackoverflow question, which seems to have excellent answers.

Kilazur
  • 2,828
  • 1
  • 21
  • 43