Nested routines with C++11 |
Top Previous Next |
What is translated > Routines > Nested routines > Nested routines with C++11 There aren't nested functions in C++, but they can be simulated by use of C++11 lambda-functions.
type TNested = class public iClassVar : Integer; function Test(iOuterParam, iTwiceParam : Integer; s : String): Integer; end;
implementation
function TNested.Test(iOuterParam, iTwiceParam : Integer; s : String): Integer; const cSeparate = ':'; var iFunctionVar : Integer;
procedure NestedTest(iInnerParam, iTwiceParam : Integer); begin result := iClassVar + iOuterParam + iFunctionVar + iInnerParam + iTwiceParam; end;
begin iClassVar := 1; iFunctionVar := 2; NestedTest1(3, 4); result := result + iTwiceParam; end;
->
class TNested : public System::TObject { typedef System::TObject inherited; public: int iClassVar; int Test(int iOuterParam, int iTwiceParam, System::String s); void InitMembers(){iClassVar = 0;} public: TNested() {InitMembers();} };
//--------------------------------------------------------------------------- int TNested::Test(int iOuterParam, int iTwiceParam, String s) { int result = 0; const DWideChar cSeparate = _T(':'); int iFunctionVar = 0; //--------------------------------------------------------------------------- auto NestedTest = [&](int iInnerParam, int iTwiceParam) -> void { result = iClassVar + iOuterParam + iFunctionVar + iInnerParam + iTwiceParam; }; iClassVar = 1; iFunctionVar = 2; NestedTest1(3, 4); result = result + iTwiceParam; return result; }
Like nested routines in Delphi lambda functions can access variables from the outer scope. The capture clause [&] ensures that access is via reference.
In the special case, that a sub-routine is called reflexively, the auto variable cannot be used. (VisualC produces the error C2064: term does not evaluate to a function taking N arguments. "The expression does not evaluate to a pointer to a function"). DelphiXE2C11 generates an explicit forward declaration in such cases. For example:
function nested : boolean;
function nested_reflexive(depth :Integer) : boolean; begin if depth = 2 then result := true else result := nested_reflexive(depth + 1); end;
begin result := nested_reflexive(0); end;
->
function<bool (int)> nested_reflexive;
bool __fastcall nested() { bool result = false;
nested_reflexive = [&](int depth) -> bool { bool result = false; if(depth == 2) result = true; else result = nested_reflexive(depth + 1); return result; }; result = nested_reflexive(0); return result; }
This compiles and works well.
|
This page belongs to the Delphi2Cpp Documentation |
Delphi2Cpp home Content |