c++ - 绑定(bind) std::function 错误

标签 c++ c++11 std-function stdbind

我在尝试使用 std::function 和 std::bind 绑定(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)

请求函数类型定义:

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。当时,lambda 有一些限制,所以 std::bind 很有意义。但这不是 lambda C++11 限制发生的情况之一,并且随着 lambda 的发展,学习使用 std::bind 在这一点上显着减少了边际效用。

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

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

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

但我认为你不应该。

关于c++ - 绑定(bind) std::function 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558244/

相关文章:

c++11 - std::function,模板参数 T(X)

c++ - 从作为模板函数参数传递的 std::function 推断返回和参数类型?

c++ - '&' 对绑定(bind)成员函数表达式错误的非法操作

c++ - "rename"禁止复制文件

c++ - 当可移植性很重要时,使用 C++ 0x/TR1 是否安全?

c++ - 使用线程停止一个 Action

c++ - 一个 const std::function 包装一个非常量 operator()/mutable lambda

c++ - 如何使用 WM_CLOSE 关闭子窗口?

c++ - 随机生成器的重复初始序列

c++ - 错误 : no matching function for call to [. ..] 注意:模板参数推导/替换失败