Thursday, November 07, 2019

You can use a C++11 range for loop over a static array

void DeviceListing::populateListing(const show showStatus)
{
  const Solid::DeviceInterface::Type needHardware[] = {
    Solid::DeviceInterface::Processor,
    Solid::DeviceInterface::StorageDrive,
    Solid::DeviceInterface::Battery,
    Solid::DeviceInterface::PortableMediaPlayer,
    Solid::DeviceInterface::Camera
  };

  clear();

  for (unsigned int i = 0; i < (sizeof(needHardware)/sizeof(Solid::DeviceInterface::Type)); i++) {
    QTreeWidgetItem *tmpDevice = createListItems(needHardware[i]);
    deviceMap[needHardware[i]] = static_cast(tmpDevice);

    if ((tmpDevice->childCount() > 0) || (showStatus == ALL)) {
      addTopLevelItem(tmpDevice);
    }
  }
}

in C++11 you can rewrite it in the much easier to read

void DeviceListing::populateListing(const show showStatus)
{
  const Solid::DeviceInterface::Type needHardware[] = {
    Solid::DeviceInterface::Processor,
    Solid::DeviceInterface::StorageDrive,
    Solid::DeviceInterface::Battery,
    Solid::DeviceInterface::PortableMediaPlayer,
    Solid::DeviceInterface::Camera
  };

  clear();
 
  for (const Solid::DeviceInterface::Type nh : needHardware) {
    QTreeWidgetItem *tmpDevice = createListItems(nh);
    deviceMap[nh] = static_cast(tmpDevice);

    if ((tmpDevice->childCount() > 0) || (showStatus == ALL)) {
      addTopLevelItem(tmpDevice);
    }
  }
}

No comments: