绑定 std::function 错误

Bind std::function error

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

在我的通信服务中 class :

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)

请求函数类型定义:

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

BindGET 错误:

error C2664: 'void RESTServer::BindGET(RequestFunction)': cannot convert argument 1 from '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;

而且效果很好。 (当然调整了所有签名方法)。

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

改变

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 几乎总是一个坏主意。 Lambda 解决同样的问题,而且几乎总是做得更好,并提供更好的错误消息。 std::bind 具有 lambda 的功能的少数情况在 C++14 中大多没有涵盖。

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

即使您掌握了 std::bind,它也有足够烦人的怪癖(比如将绑定表达式传递给绑定),避免它会有回报。

您也可以通过以下方式修复它:

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

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