gpt4 book ai didi

c++ - 如何包装 C++11 回调?

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:49 24 4
gpt4 key购买 nike

我正在使用 Casablanca C++ Rest SDK用于http连接。这是发出 http 请求的一段基本代码。

复制自Casablanca documentation :

// Creates an HTTP request and prints the length of the response stream.
pplx::task<void> HTTPStreamingAsync()
{
http_client client(L"http://www.google.com");

// Make the request and asynchronously process the response.
return client.request(methods::GET).then([](http_response response)
{
// Response received, do whatever here.
});
}

这将执行异步请求并在完成时执行回调。我需要创建自己的类来使用这些代码,并且我想将其包装到我自己的回调中。

为简单起见,假设我想创建一个类,该类具有打印 google.com 的 html 代码的方法。

所以我期待这样的事情:

MyClass myObject;
myObject.getGoogleHTML([](std::string htmlString)
{
std::cout << htmlString;
});

我搜索并阅读了相关文章,例如:

  1. C++ class member callback simple examples
  2. C++11 styled callbacks?
  3. Friday Q&A 2011-06-03: Objective-C Blocks vs. C++0x Lambdas: Fight!

但是当我在 Objective-C 中使用 completion block 时,我仍然有点困惑。如何构建这样一个包装回调的类?

最佳答案

以lambda作为一般类型。作为奖励,它可以与任何其他可调用对象一起使用。

template<typename F>
pplx::task<void> MyClass::getGoogleHTML(F f) {
http_client client(L"http://www.google.com");
return client.request(methods::GET).then(f);
}

你也可以完美转发f通过F &&f.then(std::forward<F>(f))如果你希望。如果你真的想提取一些东西给传入的 lambda,将 lambda 传递给 then捕获 f并使用提取的数据调用它。

关于c++ - 如何包装 C++11 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24434001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com