Search code examples
c++c++11vectorenumsenum-class

Keys to access vector fields - enum class or enum in namespace?


Let's say I have an alias for vector:

typedef std::vector<double> PlanetData;

And I want it's fields to be accessible via some keys:

double x = planet_data[PlanetDataKeys::PosX]; //planet_data is of type PlanetData

How can I achieve it?

I can define an enum inside a namespace:

namespace PlanetDataKeys {
  enum {
    PosX = 0,
    PosY = 1
  };
}

But enum class is safer:

enum class PlanetDataKeys {
  PosX = 0,
  PosY = 1
};

However, as implicit casting of enum class to int type is disabled, this would require to write:

double x =  planet_data[static_cast<int>(PlanetDataKeys::PosX)];

which is a bit awkward .

Which approach is better in this case and why?

EDIT Some explanation for aliasing vector:

In real code, PlanetData have ~7 fields, maybe even more if I decide to expand it. And I'm creating an instance of it while parsing a string of form data_string = "date: 2903248.12343, position=[124543254.1343214,123213.12341,63456.1234], velocity=[...". That's why I wanted it to be a vector: to use something like planet_data.push_back(ParseNextDouble(data_string));


Solution

  • Please don't expect too much functionality from a humble vector.

    Vector is not designed to access it's data with keys other than indices. Despite your examples are syntactically and semantically correct, they look like a misuse of std::vector and enum classes. Each tool has it's purpose, and vector seems to be not the best one for your task.

    Enum classes were introduced to improve type safety. With them, you'll never mix up PlanetDataKeys, SatelliteEphemeris and KeplerianOrbitElements. But in your case you finally cast any of them to int, loosing all the conquest of type-safe enums.

    As to me, it would be better to define a PlanetData class with a subscript operator which accepts PlanetDataKeys as it's argument.

    If you want to stick with vectors, I'd choose the first variant (with namespaces). It's much easier to read and write, and I'm convinced that it's not even a little safer than enum classes used this way.