A suggestion: Use an array for identifier to string conversions.
std::ostream& operator<<(std::ostream& os, ignition_parts ip)
{
static const char * names[] =
{
"Nothing",
"Distribuidor", "Tampa", "Pontos", "Vela", "Condensador"
}
// Test ip for validity first.
os << names[ip];
}
The above is not safe because if the enum
order changes, the mappings in the above table will produce incorrect results. Also, if the enum
is expanded and the array isn't, you can get a runtime buffer overrun error (nasty).
A safer method is to include the identifier in the table:
struct Entry
{
ignition_parts part_id;
const char * name;
};
const Entry name_table[] =
{
{distributor, "Distribuidor"},
{cap, "Tampa"},
{points, "Pontos"},
{plug, "Vela"},
{condenser, "Condensador"},
};
const unsigned number_of_entries =
sizeof(name_table) / sizeof(name_table[0]);
You search each entry for a matching ID, then return the name
field of the table entry.
A good benefit of this method is that you can add entries without changing code and the order is not dependent (order of entries does not matter).