【问题标题】:How to wrap a C++11 callback?如何包装 C++11 回调?
【发布时间】:2014-08-17 12:16:53
【问题描述】:

我使用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 时,我仍然有点困惑。如何构造这样一个封装回调的类?

【问题讨论】:

  • 您的意思是类似于 T 代表 lambda 并将其转发到 then?
  • @chris:是的,请建议。
  • 对不起,如果只是我对网络东西很陌生,但是您的呼叫站点 lambda 中的字符串来自哪里?
  • @chris:请看上面的lambda,你看到有一个http_response。我所期望的是将这个 http_response 传递给我班级的 lambda。 std::string 只是一个例子。

标签: c++ c++11 lambda callback casablanca


【解决方案1】:

将 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 &amp;&amp;f 和.then(std::forward&lt;F&gt;(f)) 完美转发f。如果您真的想提取一些东西以提供给传入的 lambda,请将 lambda 传递给捕获 f 的 then 并使用提取的数据调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    相关资源
    最近更新 更多