Hwa*_*n E 1 c++ stdbind cpprest-sdk
我正在尝试通过查看 cpprestSDK 的示例代码来制作服务器。但是我不知道为什么我在示例代码中绑定。
下面是示例代码。
标准文件文件
class Handler{
public:
Handler() {};
Handler(utility::string_t url);
pplx::task<void> open() { return m_listener.open(); }
pplx::task<void> close() { return m_listener.close(); }
private:
void handle_get(http_request request);
void handle_put(http_request request);
void handle_post(http_request request);
void handle_del(http_request request);
};
Run Code Online (Sandbox Code Playgroud)
处理程序
#include "stdafx.hpp"
Handler::Handler(utility::string_t url) : m_listener(url)
{
m_listener.support(methods::GET, std::bind(&Handler::handle_get, this, std::placeholders::_1));
m_listener.support(methods::PUT, std::bind(&Handler::handle_put, this, std::placeholders::_1));
m_listener.support(methods::POST, std::bind(&Handler::handle_post, this, std::placeholders::_1));
m_listener.support(methods::DEL, std::bind(&Handler::handle_del, this, std::placeholders::_1));
}
Run Code Online (Sandbox Code Playgroud)
查看支持的参考,它的定义如下。
void support (const http::method &method, const std::function< void(http_request)> &handler)
我以为我可以这样定义它:
m_listener.support(methods::GET, &Handler::handle_get);
但它失败了。
你能告诉我为什么我在绑定时使用“this”和“std::placeholders::_1”吗?
示例代码:https : //docs.microsoft.com/ko-kr/archive/blogs/christophep/write-your-own-rest-web-server-using-c-using-cpp-rest-sdk-casablanca
cpprestSDK 侦听器参考:https ://microsoft.github.io/cpprestsdk/classweb_1_1http_1_1experimental_1_1listener_1_1http__listener.html
成员函数
void support (const http::method &method,
const std::function< void(http_request)> &handler)
Run Code Online (Sandbox Code Playgroud)
期望handler是一个可调用的
http_requestvoid。一个普通的函数void handle(http_request)将匹配这个所需的签名。
如果你想注册一个(非static)成员函数,这也是可能的,但你也必须提供对象(因为非static成员函数可能不会在没有对象的情况下被调用)。
将std::bind(&Handler::handle_get, this, std::placeholders::_1)作为(一种)适配器以满足您的成员函数(this如绑定的对象)到该要求。
的std::placeholders::_1表示,其中,以(类型参数绑定http_request)到包裹构件函数调用。
一种更简单的方法是使用 lambda 作为适配器(而不是bind):
m_listener.support(methods::GET, [this](http_request http_req) { this->handle_get(http_req); });
Run Code Online (Sandbox Code Playgroud)
甚至:
m_listener.support(methods::GET, [this](http_request http_req) { handle_get(http_req); });
Run Code Online (Sandbox Code Playgroud)
进一步阅读:
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |