static_cast<type>() vs type ()

270 views Asked by At

In the "Programming: Principles and Practice Using C++", "Section 8.5.7 Argument checking and conversion" the following example is given as evidence on how to properly convert types, but never clearly explains why you would use int() vs static_cast<int>() to convert from a double to an int. However, I'm still unclear on the benefits of static_cast<int>() vs int().

void ff(int x);

void gg(double y) {
    ff(y); // how would you know if this makes sense?
    int x=y; //how would you know if this makes sense?
}
void ggg(double x) {
    int x1 = x; // truncate x
    int x2 = int(x);
    int x3 = static_cast<int>(x); // very explicit conversion (17.8)

    ff(x1);
    ff(x2);
    ff(x3);

    ff(x); // truncate x
    ff(int(x));
    ff(static_cast<int>(x)); // very explicit conversion (17.8)
}

I checked section 17.8, but still didn't find clarity on this topic. Can someone help? I'm looking for a solution that compares static_cast with function-style cast.

1

There are 1 answers

0
Oliv On

Explicit type conversion is permissive [expr.type.conv]:

If the initializer is a parenthesized single expression, the type conversion expression is equivalent to the corresponding cast expression.

On the other-hand if you use it only for fundamental types it should be fine. It should be never used in generic code:

template<class T,class...Args>
auto dangerous_construct(Args...args){
  return U(args...); //here we could have a reinterpret_cast
  }
int i;
double* v = dangerous_build<double*>(&i);//no compilation error!

If you look for a short and safe cast use the brace-style:

template<T,class...Args>
auto safe_construct(Args...args){
  return U{args...}; //OK equivalent to a static_cast + narrowing checks.
  }