C ++我不知道在使用回调函数时使用“ this”和“ std :: placeholders :: _ 1”意味着什么

问题描述

我正在尝试通过查看cpprestSDK的示例代码来构建服务器。 但是我不知道为什么要绑定示例代码

下面是示例代码

stdafx.h

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

hander.cpp

  
#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,std::placeholders::_1));
    m_listener.support(methods::POST,std::bind(&Handler::handle_post,std::placeholders::_1));
    m_listener.support(methods::DEL,std::bind(&Handler::handle_del,std::placeholders::_1));
}

请参阅支持参考,其定义如下。

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)

期望handler是具有

的可调用对象
  • 类型为http_request的参数
  • 返回类型void

普通函数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); });

甚至:

m_listener.support(methods::GET,[this](http_request http_req) { handle_get(http_req); });

更多读数: