Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Casting enumerations

Status
Not open for further replies.

azwaan

Programmer
Jan 11, 2002
42
I have a enum declared as follows

enum StatusLevels
{ eConversionStatusNone= 0,
eStatusInProgress = 1,
eStatusSuccess = 2,
eFailed = 3
} StatusLevels;

im using this within code to cast a variable of type short to the enum type as follows

StatusLevels eStatus;
eStatus=static_cast<StatusLevels> (pCommand->GetParamValue(5).iVal);

the stored proc executed returns a smallint type from sql server , but i need to check whether its a invalid value (ie.. not within 0-3)

however i cannot determine whether the cast was successful by using the above method.. is there any other way of doing this so i can determine if the operation was a success so that i can throw an exception if it failed.
 
Use
- a series of if/else tests
- a switch/case
- a lookip table
- a std::map

Eg snippets
Code:
struct {
  StatusLevels   level;
  unsigned short value;
} table[] = {
  { eConversionStatusNone, 0 },
  { eStatusInProgress, 1 },
  { eStatusSuccess, 2 },
  { eFailed, 3 }
};
for ( i = 0 ; i < 4 ; i++ ) 
  if ( inputVal == table[i].value ) 
    return table[i].level;
If it fails the lookup, raise the exception.

--
 
The cast should never fail, although it might cast it to an invalid enum value.
BTW, you could also use the enum constructor rather than a static_cast (just to make the line a bit shorter) like this:
Code:
eStatus = StatusLevels( pCommand->GetParamValue(5).iVal );
If your enum doesn't skip any values between 0 and 3 you could do this:
Code:
enum StatusLevels
{
   eConversionStatusNone= 0,
   eStatusInProgress = 1,
   eStatusSuccess = 2,
   eFailed = 3,
   eMaxStatusLevel
} StatusLevels;
Then you'd just have to test whether the value you casted is >= eMaxStatusLevel.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top