Main BLOGGER
Google
WWW THIS BLOG
Wednesday, October 05, 2005
 
C++ enum in distributed environment
http://www.cprogramming.com/tutorial/enum.html

1. enum is better than const in terms of type safety (to avoid unsencial value)
2. It is okay to convert an enum value to int but NOT vice versa.
3. It is better off using a string to convert a value to an enum value.
4. We can also use static_cast to typecast an int to an enum value.

Quoted from the above link

As already mentioned, you can't make the reverse assignment in C++ without using a typecast. There might be times when you do need to do this, but you'd like to avoid it as best you can. For instance, if you need to convert a user's input into an enumerated type, it would be a bad idea to just typecast the variable to an int:

wind_directions_t wind_direction = NO_WIND;

std::cin >> static_cast( wind_direction );

This would let the user input any value at all and, almost as bad, force the user to know the range of values that the enum could take on. A much better solution would be to shield the user from the enumeration by asking for a string and then validating the input by comparing it to the possible input strings to choose which constant to assign the enum. For instance,
std::cout << "Please enter NORTH, SOUTH, EAST, WEST, or NONE for our wind direction";
std::cout << std::endl;

string input_wind_dir;
cin >> wind_directions_t wind_dir;

if ( user_wind_dir == "NORTH" )
{
wind_dir = NORTH_WIND;
}
else if ( user_wind_dir == "SOUTH" )
{
wind_dir = SOUTH_WIND;
}
else if ( user_wind_dir == "EAST" )
{
wind_dir = EAST_WIND;
}
else if ( user_wind_dir == "WEST" )
{
wind_dir = WEST_WIND;
}
else if ( user_wind_dir == "NONE" )
{
wind_dir = NO_WIND;
}
else
{
std::cout << "That's not a valid direction!" << std::endl;
}




<< Home

Powered by Blogger

Google
WWW THIS BLOG