ThFl ThFl - 2 years ago 203
C++ Question

C++ equivalent for C# Action passing

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download