2014-06-26 37 views
1

我使用Casablanca C++ Rest SDK進行http連接。這是一個發出http請求的基本代碼片段。如何包裝C++ 11回調?

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。我怎樣才能構造一個包裝回調的類?

+0

你的意思是像'T'代表拉姆達,只是轉發到'然後'? – chris

+0

@chris:是的,請提出建議。 –

+0

對不起,如果它只是我對網絡新東西,但你的callsite lambda字符串來自哪裏? – chris

回答

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通過F &&f.then(std::forward<F>(f))如果你想。如果您實際上想要提取某些內容給傳入的lambda表達式,請將一個lambda表達式傳遞給then,該表達式捕獲f並將其與提取的數據一起調用。