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?

4
  • You mean something like a T representing the lambda and just forwarding it to then? Commented Jun 26, 2014 at 15:05
  • @chris: yes, please suggest. Commented Jun 26, 2014 at 15:06
  • Sorry if it's just me being new-ish to web stuff, but where does the string in your callsite lambda come from? Commented Jun 26, 2014 at 15:16
  • @chris: please look at the lambda above, you see that there is a http_response. All I expected is to have this http_response passed to my class's lambda. std::string is a just an example. Commented Jun 26, 2014 at 15:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.