CuriousKimchi CuriousKimchi - 1 month ago 7
C++ Question

How do you know if you can static_cast a type into a different type?

Here's a quote from wikipedia description for static_cast.

"The type parameter must be a data type to which object can be converted via a known method, whether it be a builtin or a cast. The type can be a reference or an enumerator. All types of conversions that are well-defined and allowed by the compiler are performed using static_cast."

How do you figure out this "known method"?

Answer

A list of conversions that can be performed by static_cast is given in the keywords documentation:

  • Base class pointer (resp. reference) to derived class pointer (resp. reference)
  • Any implicit conversion
  • A conversion that calls an explicit constructor or explicit conversion function
  • Lvalue to xvalue
  • Any type to void
  • Between arithmetic and enum types, or two different enum types
  • From pointer to member of derived class, to pointer to member of base class, provided the pointed-to types match
  • void* to T*, where T is an object type

In the case of the second and third bullet points, there may be multiple possible conversion sequences. Overload resolution is used to select the best one. It's true that sometimes it might not be obvious which one is the best, the one that the compiler will pick (which is why it's a good idea to not go overboard with overloaded constructors and conversion functions). If overload resolution is ambiguous, the program will not compile.