【发布时间】:2020-10-26 08:56:49
【问题描述】:
我在 C++ 中的函数之间传递值时遇到问题。我在下面添加代码。在 mqttReceive 中,接收到 JSON 格式的 MQTT 消息,并在 send() 中再次发送以在 void send() 中接收。但是,我尝试将收到的消息声明为自动,但它不起作用。我错过了什么?
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 字符串。谢谢
【问题讨论】:
-
编译器需要知道
msg的确切类型。 -
Auto 不是 msg 的正确类型?
-
@thecoder,
auto不是类型。它是一个在特定上下文中工作的占位符,用于告诉编译器推断类型。 -
试着把 auto 想象成一个别名,在 cpp 文件中,编译器可以从
mqttClient->consume_message()推断出返回的类型,所以很高兴调用这个 auto。但是在 hpp 中,当为::send(...)定义函数签名时,编译器无事可做。如果您希望 send 是通用的,您可以考虑模板化send否则您需要更具体。