考虑以下两种方法:
QVector<QPointF> DataProvider::getPointsSize()
{
QVector<QPointF> points;
foreach (Database::TbRawInItem item, rawInData)
points << QPointF(item.timestamp.toTime_t(), item.data.size());
return points;
}
QVector<QPointF> DataProvider::getPointsPacketCounter()
{
QVector<QPointF> points;
foreach (Database::BeaconItem item, beaconData)
points << QPointF(item.timestamp.toTime_t(), item.packetCounter);
return points;
}
我想将它改进为getPoints
方法,该方法将被称为传递foeach参数。像这样:
getPoints(TbRawInItem, rawInData);
getPoints(BeaconItem, beaconData);
班级成员rawInData
和beaconData
定义为:
QVector<Database::TbRawInItem> rawInData;
QVector<Database::BeaconItem> beaconData;
item
是一个结构:
struct TbRawInItem {
unsigned int id;
QDateTime timestamp;
QByteArray data;
char interface;
};
struct BeaconItem {
QDateTime timestamp;
unsigned int packetCounter;
unsigned int cmdRxCounter;
unsigned int cmdValidCounter;
double battVoltage;
double totalSysCurrent;
double battTemperature;
double photoVoltaicVoltage1;
double photoVoltaicVoltage2;
double photoVoltaicVoltage3;
double photoCurrent;
};
我的问题是如何处理item
结构?
答案 0 :(得分:1)
unsigned int getSize(Database::TbRawInItem const &item) {
return item.data.size();
}
unsigned int getSize(Database::BeaconItem const &item) {
return item.packetCounter;
}
// you need to create an overload for each type of item
// If you have many item types and some of them get the size the same way
// you can group them together (just one function for all) with
// templates and SFINAE
// That is an advanced tehnique though.
template <class T>
QVector<QPointF> DataProvider::getPoints(T const &data) {
QVector<QPointF> points;
foreach (T item, data)
points << QPointF(item.timestamp.toTime_t(), getSize(data));
return points;
}
getPoints(rawData); // T will be deduced as Database::TbRawInItem
getPoints(beaconData); // T will be deduced as Database::BeaconItem
或与lambdas:
template <class T, class Func>
QVector<QPointF> DataProvider::getPoints(T const &data, Func const &get_size) {
QVector<QPointF> points;
foreach (T item, data)
points << QPointF(item.timestamp.toTime_t(), get_size(data));
return points;
}
getPoints(rawData, [](Database::TbRawInItem const &item) {
return item.data.size();}));
getPoints(beaconData, [](Database::BeaconItem const &item) {
return item.packetCounter;}));
或介于两者之间
声明:
foreach
我认为这是qt
的事情。不过它的概念是一样的。