我在C++中的函数之间传递值时遇到问题。我在下面添加代码。在mqttReceive中,接收JSON中的MQTT消息,并在send((中再次发送该消息,以便在void send(((中接收。然而,我已经尝试将接收到的消息声明为auto,但它不起作用。我缺少什么?
cpp:
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)
{
...
}
hpp:
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字符串。感谢
使用auto
作为参数是C++20的一项功能,一些编译器在早期版本中支持它作为扩展,但在那里不支持ISO。
函数模板的语法需要C++20。对于C++17及更旧版本,您需要更改以下内容:
void MqttApplication::send(auto msg)
至:
template <typename T>
void MqttApplication::send(T msg)
两者都是等效的,但C++20版本更短。请参见缩写函数模板。
我想知道你预计会发生什么?用";自动;在函数声明中,编译器无法知道类型是什么,因此拒绝编译。这与";auto x=3"其中编译器知道x的类型应该与3的类型相同。
如果你的编译器理解概念,你也理解概念,那么你就可以构建你的代码,但这需要你理解一个全新的C++特性。