QT 5.1 提取信号槽连接公共逻辑以消除冗余代码
Got it, let's fix that redundant Qt connect code you're dealing with in Qt 5.1. Here's a straightforward, clean approach to extract the common logic into a reusable helper method:
First, let's recap the problem: your Client::connectToSignals() has repeated QObject::connect calls where mqtt.get() (the signal emitter) and this (the receiver context) are always the same. We can wrap that fixed logic into a helper to cut down on repetition.
Step 1: Add a Template Helper to Your Client Class
Since Qt signals and slots can have different signatures, a template function is perfect here—it'll handle any valid signal-slot pair between your MQTT client and the Client class.
Add this to your client.h inside the Client class definition:
class Client { // ... existing class members ... private: // Helper to connect MQTT signals to Client slots without repetition template<typename SignalType, typename SlotType> void connectMqttSignal(SignalType signal, SlotType slot) { QObject::connect(mqtt.get(), signal, this, slot); } };
Step 2: Refactor Your connectToSignals() Method
Now you can rewrite client.cpp's connectToSignals() to use the helper, ditching the redundant parts:
void Client::connectToSignals() { connectMqttSignal(&MqttClient::connected, &Client::onConnected); connectMqttSignal(&MqttClient::disconnected, &Client::onDisconnected); // Add more signal-slot pairs here with just two arguments! }
Why This Works
- No more repetition: You don't have to type
mqtt.get()andthisevery time you add a new connection. - Type-safe: The template ensures you can only pass valid signals from
MqttClientand slots fromClient—Qt's compile-time checks still apply. - Cleaner code: Your
connectToSignals()method now focuses solely on which signals map to which slots, not the boilerplate connect logic.
Optional: Add Debugging Checks
If you want to catch invalid connections early during development, extend the helper with an assertion:
template<typename SignalType, typename SlotType> void connectMqttSignal(SignalType signal, SlotType slot) { bool connectionSuccess = QObject::connect(mqtt.get(), signal, this, slot); Q_ASSERT(connectionSuccess); // Triggers if the signal/slot pair is invalid }
内容的提问来源于stack exchange,提问作者Matthias Herrmann

