c++ 中是否有等同于目标 c 中的"block"的功能?

Is there a feature in c++ that equivalent to the "block" in objective c?

本文关键字:block 功能 中的 是否 等同于 目标 c++      更新时间:2023-10-16

正如标题所说。c++中是否有与目标c中的"块"等效的特征?谢谢

lambdas?

[&](){
    printf("Hello!");
}

是的,您可以在c++11中使用std::function(lambda函数)。这些函数的工作原理与目标c 中的块类似

定义

typedef std::function<void(std::string message, bool status)> LoginCallback

使用类内函数

void loginUser(std::string email, std::string password, LoginCallback loginCallback)

假设上述函数在LoginClass 中

函数调用

loginClassObj.loginUser("abc@xyz.com", "password", [this](std::string message, bool status){//Callback will received here});

它是C的非标准扩展。它是lambda函数的闭包,基本上它们是类似于未命名函数的实体,包含了可以调用的代码。例如,它们有助于编写事件驱动的代码,在这些代码中,回调被详尽地使用。请参阅此