Here's another common approach to enum-string conversions which is fairly easy to maintain:
Code:
#include <iostream>
#include <vector>
#include <iterator>
class foo
{
public:
enum id
{
zero,
one,
two,
three,
four,
/*
Remember: add additional enums before this one!
*/
enum_count
};
std::string enum_to_string( id index ) const
{
if( index >= enum_count )
return "<<undefined>>";
static std::string
names[ enum_count ] =
{
"zero",
"one",
"two",
"three",
"four"
};
return names[ index ];
}
std::vector< std::string > get_enum_strings( void ) const
{
std::vector< std::string >
result;
for( size_t index = 0; index < enum_count; ++index )
result.push_back( enum_to_string( id( index ) ) );
return result;
}
};
int main( void )
{
using namespace
std;
foo
f;
cout << f.enum_to_string( foo::four ) << endl;
cout << f.enum_to_string( foo::id( 4 ) ) << endl;
cout << f.enum_to_string( foo::id( 7 ) ) << endl;
vector< string >
v = f.get_enum_strings( );
copy( v.begin( ), v.end( ), ostream_iterator< string >( cout, "\n" ) );
}
Hth.