【问题标题】:Return a value from lambda function inside a function c++从函数c ++中的lambda函数返回一个值
【发布时间】:2018-07-05 10:28:51
【问题描述】:

我正在使用 RabbiMQ (RPC),我想从 lambda 函数返回一个值。我正在从 main.cpp 调用此函数,但返回值与预期不符(lambda 函数内的值与预期相符)。什么是正确的语法?

我的代码:

bool RabbitMqHandler::sendResultToUserCountService(analyze_result result, Camera *cam)
{
    std:: string queueName = "userCountServiceReceiveRPC" + std::to_string(cam->getUserGroupId());

    const std::string correlation("2");

    SimplePocoHandler handler("localhost", 5672);

    AMQP::Connection connection(&handler, 
                                AMQP::Login("localhost","123456!"),"/");

    bool isExist;
    AMQP::Channel channel(&connection);
    AMQP::QueueCallback callback = [&](const std::string &name,
                                       int msgcount,
                                       int consumercount)
    {

         ProtobufLPR::CarResult carResult;

         carResult.set_licensenumber(result.LicenseNumber);
         carResult.set_analyzetime(result.Date);

         std::string buf;
         carResult.SerializeToString(&buf);

         AMQP::Envelope env(buf);
         env.setCorrelationID(correlation);
         env.setReplyTo(name);
         channel.publish("", queueName, env);
         std::cout << "Requesting " << result.LicenseNumber << std::endl;
    };

    channel.declareQueue(AMQP::exclusive).onSuccess(callback);

    auto receiveCallback = [&](const AMQP::Message &message,
                               uint64_t deliveryTag,
                               bool redelivered) ->bool
    {
        if(message.correlationID() != correlation)
            return 1;

        std::cout<<"Got " << message.message() <<std::endl;
        handler.quit();
        istringstream(message.message()) >> isExist;
        return isExist;
      };

      channel.consume("", AMQP::noack).onReceived(receiveCallback);
      handler.loop();
}

【问题讨论】:

  • 从 lambda 返回内容的语法是 return ...;,就像你正在做的那样。请尝试创建一个minimal reproducible example。无法知道这些有限的信息有什么问题。
  • 大概你想让 sendResultToUserCountService 从那里的 lambda 中返回。最简单的方法可能是在外部函数中声明一个bool ret = false;,从lambda内部修改它,在外部函数中修改return ret
  • lambda 函数中打印的值与返回的值是否不同?为 isExist 做一个 cout 来检查这个。也许您不需要使用 [&] 而只需使用 []?
  • 你的receiveCallback lambda 可能在sendResultToUserCountService 返回后被调用,通过引用([&amp;])捕获本地堆栈变量isExist 将导致一个悬空引用,因此你返回一些垃圾你的 lambda。
  • @yussuf 回调更可能是从handler.loop() 内部调用的,在这种情况下引用不是问题,但我对 RabbitMQ 不够熟悉,无法确定。

标签: c++ lambda rabbitmq


【解决方案1】:

这是一个从 lambda 函数返回值的示例。 Live demo.

#include <iostream>
#include <iomanip>

int main() {
    auto greater_than_30 = [](int value) {
        return value > 30;
    };

    std::cout << "is 45 greater than 30? " << std::boolalpha
        << greater_than_30(45) << "\n";

    return 0;
}

【讨论】:

    猜你喜欢
    • 2019-04-10
    • 2021-04-02
    • 2012-12-29
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 2022-04-29
    相关资源
    最近更新 更多