6 ms·
2 places is better than N places. At the cost of slightly heavier enum declarations (2 places), you get rid of tests throughout the code for particular enum val
by JoeAltmaier 12y ago
2 places is better than N places. At the cost of slightly heavier enum declarations (2 places), you get rid of tests throughout the code for particular enum values.
Also consider inheiritance and enums. Derived classes have to jump through hoops to extend enum space e.g. enum { tractor = truck+1, crane, bulldozer}; where truck was the last enum value in the base class.
With the tuple method, you just add some more tuples.
- stinos 12y agoYes of course inheritance (if you can even call it that) is problematic and indeed one, if not the whole, point of the solution is having to add an antry means having to do it in one place only, but my question remains: does it have to be with a macro? I threw something together and this seems sort of equivalent but (imo) with less of the uglyness? enum class VehicleType { Car, Bicycle }; using tuple = std::tuple< std::string, int, int >; using map = std::map< VehicleType, tuple >; const map VehicleTypes = { { VehicleType::Car, tuple( "car", 4, 10 ) }, { VehicleType::Bicycle, tuple( "bicycle", 3, 20 ) } }; const tuple& get_it( VehicleType type ) { static tuple def( "unknown", -1, -1 ); auto it = VehicleTypes.find( type ); return it == VehicleTypes.end() ? def : it->second; } std::string getVehicleTypeName( VehicleType type ) { return std::get< 0 >( get_it( type ) ); }