C ++ Lambda-错误:没有匹配的函数可调用 [英] C++ Lambda - error: no matching function for call to

查看:206
本文介绍了C ++ Lambda-错误:没有匹配的函数可调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将lambda作为参数传递给函数,但一旦尝试访问在外部声明的lambda内部的变量,构建就会失败:错误:没有匹配的函数可以调用' AWS :: subscribe(char [128],mainTask(void *):::< lambda(AWS_IoT_Client *,char *,uint16_t,IoT_Publish_Message_Params *,void *)>)'

I am trying to pass a lambda as parameter to a function but once I attempt to access a variable inside the lambda which was declared outside, the build fails: error: no matching function for call to 'AWS::subscribe(char [128], mainTask(void*)::<lambda(AWS_IoT_Client*, char*, uint16_t, IoT_Publish_Message_Params*, void*)>)'

我以为 [&] 将负责捕获变量。我还尝试了 [=] 以及 [someVar] [& someVar]

I was thinking that the [&] would take care of capturing variables. I also tried [=] as well as [someVar], [&someVar].

我正在使用C ++ 11。

I'm using C++11.

char someVar[128];

aws->subscribe(
  topic,
  [&] (AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData) {
    char *text = (char *)params->payload;
    sprintf(someVar, "%s", text);
  }
);

从AWS库中:

void AWS::subscribe(const char *topic,
                    pApplicationHandler_t iot_subscribe_callback_handler) {
  m_error =
      ::aws_iot_mqtt_subscribe(&m_client, topic, (uint16_t)std::strlen(topic),
                              QOS1, iot_subscribe_callback_handler, NULL);

}


推荐答案

问题是 AWS :: subscribe 函数需要函数指针,而不是lambda。无需捕获的lambda可以转换为函数指针,但是带有捕获(即状态)的lambda不能转换。

The issue is that the AWS::subscribe function expects a function pointer, not a lambda. Capture-less lambdas can be converted to function pointers, but lambdas with captures (i.e. state) cannot.

您可以在签名中看到常规解决方案:有一个 void * 参数,您应该将所有特定于回调的数据打包到其中。大概这是 aws_iot_mqtt_subscribe 的最后一个参数,您当前将其设置为 NULL (最好使用 nullptr btw)。

You can see the "conventional" solution to this already in the signature: There is a void* parameter that you should pack all your callback-specific data into. Presumably this is the last argument of aws_iot_mqtt_subscribe that you currently set to NULL (prefer using nullptr btw).

这比使用lambda更为丑陋,但这基本上是C兼容库接口的唯一选择:

This is uglier than using lambdas, but it's basically the only option for C-compatible library interfaces:

// Your callback (could also be a capture-less lambda):
void callbackFunc(/* etc. */, void *pData) 
{
    std::string* someVarPtr = static_cast<std::string*>(pData);
    char *text = (char *)params->payload;
    sprintf(*someVarPtr, "%s", text);
}

// To subscribe:
std::string someVar;
void* callbackData = &someVar; // Or a struct containing e.g. pointers to all your data.
aws_iot_mqtt_subscribe(/* etc. */, callbackFunc, callbackData);

这篇关于C ++ Lambda-错误:没有匹配的函数可调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆