A CeePlusPlus operator which performs relatively typesafe casts. Spelled:
static_cast<type>(yo)
All elaborate_cast<> operators have these benefits:
- they have a name, not just ()
- they restrict their input and output types to a subset of all possible type combinations. Failing the check creates a diagnostic at compile time.
Any C-style typecast can convert to one-and-only-one elaborate_cast<>, but dynamic_cast<> cannot convert to a C-style cast. (If that fails, the C-style typecast will jam raw bits into an
lvalue without complaint.)
The types of casts allowed are (some casts are covered by more than one of the below; no complaints please that the list is redundant)
- Any cast which is allowed implicitly (without a cast operator)
- Typecasts from one object to another where a cast function (operator T--see OperatorTee?)
- Typecasts from pointer/reference to a subtype to a pointer/reference to a supertype
- Typecasts from any pointer to void *
- Numerical conversions--double to int, int to short, short to int. Note that "narrowing" conversions are allowed; though if you try one without an explicit cast operator you will get a warning.
Note also that "typesafe" does NOT exclude undefined behavior: Using static_cast to "downcast" some Base class pointer or reference to one of its Derived classes does not ensure that the referenced object
really is of the target class. (Use
DynamicCast to add appropriate runtime checks.)
CategoryCpp