结构的通用类型

时间:2015-01-08 19:05:46

标签: c++ qt

考虑以下两种方法:

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);

班级成员rawInDatabeaconData定义为:

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结构?

1 个答案:

答案 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的事情。不过它的概念是一样的。
  • 我没有编译它,因为我没有MCVE因此可能存在语法错误。