首页 > 解决方案 > 函数 C++ 中的 Auto 变量出错

问题描述

我在 C++ 中的函数之间传递值时遇到问题。我在下面添加代码。在 mqttReceive 中,接收到 JSON 格式的 MQTT 消息,并在 send() 中再次发送以在 void send() 中接收。但是,我尝试将收到的消息声明为自动,但它不起作用。我错过了什么?

cp:

void MqttApplication::mqttReceive()
{
    try {
        
        mqttClient->start_consuming();
        mqttClient->subscribe(TOPIC, QOS)->wait();
        
    }
    catch (const mqtt::exception& exc) {
        cerr << exc.what() << endl;
        return;
    }

    
    while (true) {
        auto msg = mqttClient->consume_message();   
        

        try {               
            send(msg);
        }
        catch (const mqtt::exception& exc) {
            cerr << exc.what() << endl;
            return;
        }

        if (msg->get_topic() == "command" &&
                msg->to_string() == "exit") {
            cout << "Exit command received" << endl;
            break;
        }

        cout << msg->get_topic() << ": " << msg->to_string() << endl;
    }
}



void MqttApplication::send(auto msg)
{
    ...
}

惠普:

class MqttApplication : public Application
    {
    private:    
    
        void send(const auto msg);
    
        void mqttReceive();
        

错误:

In file included from /home/mqtt_application.cpp:1:
/home/mqtt_application.hpp:26:24: warning: use of ‘auto’ in parameter declaration only available with ‘-fconcepts-ts’
   26 |     void send(const auto& msg) override;
      |                        ^~~~
/home/mqtt_application.hpp:26:35: error: member template ‘void MqttApplication::send(const auto:1&)’ may not have virt-specifiers
   26 |     void send(const auto& msg) override;
      |                                   ^~~~~~~~
/home/mqtt_application.cpp:320:34: warning: use of ‘auto’ in parameter declaration only available with ‘-fconcepts-ts’
  320 | void MqttApplication::send(auto& msg)
      |                                  ^~~~
/home/mqtt_application.cpp:320:6: error: no declaration matches ‘void MqttApplication::send(auto:2&)’
  320 | void MqttApplication::send(auto& msg)
      |      ^~~~~~~~~~~~~~~~~~
In file included from /home/mqtt_application.cpp:1:
/home/mqtt_application.hpp:26:10: note: candidate is: ‘template<class auto:1> void MqttApplication::send(const auto:1&)’
   26 |     void send(const auto& msg) override;
      |          ^~~~~~~
In file included from /home/mqtt_application.cpp:1:
/home/mqtt_application.hpp:15:7: note: ‘class MqttApplication’ defined here
   15 | class MqttApplication : public Application
      |       ^~~~~~~~~~~~~~~~~~
tools/mqtt.dir/build.make:62: recipe for target 'tools/mqtt.dir/mqtt_application.cpp.o' failed
make[2]: *** [tools/mqtt.dir/mqtt_application.cpp.o] Error 1
CMakeFiles/Makefile2:834: recipe for target 'tools/mqtt.dir/all' failed
make[1]: *** [tools/mqtt.dir/all] Error 2
Makefile:129: recipe for target 'all' failed
make: *** [all] Error 2

我正在使用 C++14 进行编译。我已经尝试了所有类型的配置,字符串、int 等。输入是一个常规的 JSON 字符串。谢谢

标签: c++functionauto

解决方案


使用auto作为参数是C++20 的一个特性,一些编译器支持它作为早期版本的扩展,但它不是 ISO。


推荐阅读