_di_TFunc__2 - C++ Builder

C++ Builder 参考手册 ➙ System::Sysutils ➙ _di_TFunc__2


头文件:#include
命名空间:System::Sysutils
类型定义:

template using _di_TFunc__2 = System::DelphiInterface>;

C++ 匿名函数 / lambda 表达式接口:有一个参数、有返回值的匿名函数 / lambda 表达式,C++ Builder 采用这个接口让 lambda 表达式与 Delphi 的匿名函数兼容。


参数:这个 lambda 表达式或匿名函数有一个参数,类型为模板参数 T,
返回值:为模板参数 TResult 类型;


  • 调用 _di_TFunc__2::Invoke(); 可以执行 lambda 表达式。
  • 如果函数的参数是这个类型的,可以采用继承 System::TCppInterfacedObject> 并且重载 Invoke 函数作为这个参数来代替 lambda 表达式,请参考本文后面及 TThread::CreateAnonymousThread 的例子。
  • 使用 _di_TFunc__2 这个类型需要 clang 编译器

例1:写一个函数 MyFunc,参数为与 Delphi 匿名函数兼容的 lambda 表达式,lambda 表达式参数为 int 类型,返回值为 UnicodeString 类型

void TForm1::MyFunc(_di_TFunc__2 pLambda)
{
    int i = 0;
    UnicodeString s;
    while(!(s=pLambda->Invoke(i++)).IsEmpty())
    {
        ShowMessage(s);
    }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    std::auto_ptrsl(new TStringList);
    sl->Text = L"Hello, Hsuanlu!\r\n玄坴,你好!";

    MyFunc([&,this](int i)->UnicodeString {
        return i < sl->Count ? (*sl)[i] : L"";
    });
}

运行结果:两次弹出信息,分别为 sl 的两行内容

运行结果1
运行结果2

例2:依然是前面例1的 MyFunc 函数,不用 lambda 表达式,采用继承 System::TCppInterfacedObject> 的方法调用这个函数

void TForm1::MyFunc(_di_TFunc__2 pLambda)
{
    int i = 0;
    UnicodeString s;
    while(!(s=pLambda->Invoke(i++)).IsEmpty())
    {
        ShowMessage(s);
    }
}

class TMyProc : public TCppInterfacedObject>
{
public:
    UnicodeString __fastcall Invoke(int i) // 这里是调用 lambda 执行的内容
    {
        switch(i)
        {
            case 0: return L"Hello, Hsuanlu!";
            case 1: return L"玄坴,你好!";
        }
        return L"";
    }
};

//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    MyFunc(new TMyProc()); // 用 TMyProc 对象代替 lambda,自动销毁
}

相关:

  • System::Sysutils::_di_TFunc__1
  • System::Sysutils::_di_TFunc__2
  • System::Sysutils::_di_TFunc__3
  • System::Sysutils::_di_TFunc__4
  • System::Sysutils::_di_TFunc__5
  • System::Sysutils::_di_TPredicate__1
  • System::Sysutils::_di_TProc
  • System::Sysutils::_di_TProc__1
  • System::Sysutils::_di_TProc__2
  • System::Sysutils::_di_TProc__3
  • System::Sysutils::_di_TProc__4
  • System::Sysutils
  • System::TCppInterfacedObject
  • System::DelphiInterface
  • System
  • TThread::CreateAnonymousThread

C++ Builder 参考手册 ➙ System::Sysutils ➙ _di_TFunc__2

你可能感兴趣的:(_di_TFunc__2 - C++ Builder)