1

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.

4

1 回答 1

1

显式类型转换是允许的[expr.type.conv]

如果初始值设定项是带括号的单个表达式,则类型转换表达式等价于相应的强制转换表达式

另一方面,如果您仅将其用于基本类型,那应该没问题。它不应该在通用代码中使用:

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!

如果您寻找一个简短而安全的演员表,请使用大括号样式:

template<T,class...Args>
auto safe_construct(Args...args){
  return U{args...}; //OK equivalent to a static_cast + narrowing checks.
  }
于 2018-11-25T22:02:25.510 回答