Re: cast to an enum does not throw errors even for invalid values

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Shriramana,

> If an error is not called, I feel it defeats the very meaning of
> casting, to convert an object of one type to an object of another type.
> When there is no equivalent object of the target type, how can the
> casting happen?

It appears you have misunderstood what a cast operation means in this
situation.  Both the C-style cast, and the static_cast.

It means that you, the programmer, have vouched that the value being cast is
appropriate for what is being cast to.

That, obviously, is NOT what you desire.  You want some insurance that the
right hand value is checked and verified to be cast to the left hand BODY
value.

You should write and use this routine:

BODY ConvertToBODY(int i)
{
  BODY result = SUN;

  switch(i)
  {
    case SUN: result = SUN; break;
    case MOON: result = MOON; break;
    case STAR: result = STAR; break;
    default: throw "out of BODY range error";
  }

  return result;
}

It is, perhaps, unfortunate that the compiler does not synthesize this for
you.  But that's just not C++.

HTH,
--Eljay


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux