CuriousKimchi
CuriousKimchi

Reputation: 235

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"?

Upvotes: 1

Views: 943

Answers (2)

Brian Bi
Brian Bi

Reputation: 119164

Here's a list of conversions that can be performed by static_cast:

  • 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.

Upvotes: 4

yuvi
yuvi

Reputation: 1092

Actually, static_cast should be used instead of implicit type conversions.

e.g. You declare a function -

void fun(int a)
{
   std::cout << a;
}

So, fun accepts an int. But, if you call it like -

float b = 1.2;
fun(b);

Now, fun(b) is valid & it will compile & will print 1. Here, b which is actually float has been implicitly converted to int. In a large program, this may cause some bugs which are difficult to find. So, to make such conversions explicit, we use static_cast as -

fun(static_cast<int>(b));

Now, when to use static_cast is totally dependent on programmer's understanding. Because, compiler doesn't perform any runtime check on static_cast. Hence, it is left to the programmer to verify the result of a static_cast conversion are safe.

Upvotes: 0

Related Questions