QT 多级嵌套结构体并遍历其成员-模板和宏定义
多级嵌套结构体并遍历其成员是一个复杂的任务。为了实现这一目标,可以结合模板和宏定义来简化代码。以下是一个示例,展示了如何使用模板和宏定义来遍历嵌套结构体的成员。
#include <QDebug>
#include <cstdint>
// 假设这些是你的结构体定义
struct BaseMeterParam_Type {
int param1;
float param2;
};
struct NetParam_Type {
QString ipAddress;
int port;
};
struct TimingUploadParam_Type {
int interval;
bool enabled;
};
struct LadderParam_Type {
int stepCount;
float stepValue;
};
struct DeviceParam_Type {
BaseMeterParam_Type mt_BaseMeter;
NetParam_Type mt_Net;
TimingUploadParam_Type mt_TimingUpload;
LadderParam_Type mt_RunLadder;
uint16_t m_None;
uint16_t m_Crc16;
};
// 模板函数,用于打印结构体成员
template<typename T>
void printMember(const QString& name, const T& value) {
qDebug() << name << ":" << value;
}
// 宏定义,用于遍历结构体成员
#define PRINT_MEMBER(member) printMember(#member, deviceParam.member)
// 遍历DeviceParam_Type的成员
void traverseDeviceParam(const DeviceParam_Type& deviceParam) {
PRINT_MEMBER(mt_BaseMeter.param1);
PRINT_MEMBER(mt_BaseMeter.param2);
PRINT_MEMBER(mt_Net.ipAddress);
PRINT_MEMBER(mt_Net.port);
PRINT_MEMBER(mt_TimingUpload.interval);
PRINT_MEMBER(mt_TimingUpload.enabled);
PRINT_MEMBER(mt_RunLadder.stepCount);
PRINT_MEMBER(mt_RunLadder.stepValue);
PRINT_MEMBER(m_None);
PRINT_MEMBER(m_Crc16);
}
int main() {
DeviceParam_Type deviceParam = {
{1, 2.0f},
{"192.168.1.1", 8080},
{60, true},
{10, 0.5f},
0,
0xFFFF
};
traverseDeviceParam(deviceParam);
return 0;
}
原文地址:https://blog.csdn.net/qq_27741499/article/details/144356755
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!