dimanche 26 septembre 2021

How to make a simple loop more generic

The below method will concatenate all warnings into one string. It works but obviously need to create almost the same method again for info and error.

struct MyItem
{
  std::vector<std::string> errors;
  std::vector<std::string> warnings;
  std::vector<std::string> infos;
};
std::vector<MyItem> items;


std::string GetWarnings()
{
  std::string str;
  for (auto item : items)
  {
    for (auto warn : item.warnings)
    {
      str += warn;
      str += " ";
    }
  }
  return str;
}

What would be a good generic way to implement one "Concatenate" method? One solution would be to define an enum (error\warning\item), pass it as input argument and make a switch case on argument value. Any more elegant solutions?

Aucun commentaire:

Enregistrer un commentaire