1

I'm using Casablanca C++ Rest SDK for http connections. Here is a basic piece of code that makes a http request.

Copied from 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.
    });
}

This will do an asynchronous request and do a callback when done. I need to make my own class that uses these codes and I want to wrap it to my own callback.

For simplicity, assume that I want to make a class that has method which print html code of google.com.

So I expected something like this:

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

I searched and read related articles like:

  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!

But I'm still a bit confused as I get used with completion block in Objective-C. How can I construct such a class that wraps callback?

Community
  • 1
  • 1
Thanh-Nhon Nguyen
  • 3,402
  • 3
  • 28
  • 41

1 Answers1

1

Take the lambda as a general type. As a bonus, it'll work with any other callable object.

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);
}

You could also perfectly forward f via F &&f and .then(std::forward<F>(f)) if you wish. If you're actually looking to extract something to give to the passed-in lambda, pass a lambda to then that captures f and calls it with that extracted data.

chris
  • 60,560
  • 13
  • 143
  • 205