首页 文章

绑定std :: function错误

提问于
浏览
1

尝试使用std :: function和std :: bind绑定方法时遇到问题 .

在我的CommunicationService类中:

this->httpServer->BindGET(std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1));

CommunicationService :: ManageGetRequest签名:

MessageContent CommunicationService::ManageGetRequest(std::string uri, MessageContent msgContent)

BindGET签名:

void RESTServer::BindGET(RequestFunction getMethod)

RequestFunction typedef:

typedef std::function<MessageContent(std::string, MessageContent)> RequestFunction;

BindGET上的错误:

错误C2664:'void RESTServer :: BindGET(RequestFunction)':无法转换参数1来自'std :: _ Binder <std :: _ Unforced,MessageContent(__ cdecl communication :: CommunicationService :: *)(std :: string,MessageContent) ,communication :: CommunicationService * const,const std :: _ Ph <1>&>'to'RequestFunction'

之前,我的RequestFunction是这样的:

typedef std::function<void(std::string)> RequestFunction;

它工作得很好 . (当然,调整了所有签名方法) .

我不明白导致错误的原因 .

1 回答

  • 8

    更改

    this->httpServer->BindGET(
      std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1)
    );
    

    this->httpServer->BindGET(
      [this](std::string uri, MessageContent msgContent) {
        this->ManageGETRequest(std::move(uri), std::move(msgContent));
      }
    );
    

    使用 std::bind 几乎总是一个坏主意 . Lambdas解决了同样的问题,并且几乎总是做得更好,并提供更好的错误消息 . std::bind 具有lambdas特征的少数情况并不是C 14主要涵盖的地方 .

    std::bind 是在pre-lambda C 11中用 boost::bind 编写的,然后同时将lambdas带入标准 . 当时,lambdas有一些限制,所以 std::bind 是有道理的 . 但这并不是lambdas C 11限制发生的情况之一,而且随着lambda的功率增长,学习使用 std::bind 在这一点上显着降低了边际效用 .

    即使你掌握了 std::bind ,它也有足够烦人的怪癖(比如传递一个绑定表达式来绑定),避免它有收益 .

    你也可以修复它:

    this->httpServer->BindGET(
      std::bind(&CommunicationService::ManageGETRequest, this, std::placeholders::_1, std::placeholders::_2)
    );
    

    但我不认为你应该这样做 .

相关问题