在“编程:使用C++的原则和实践”的“8.5.7节参数检查和转换”中,下面的示例是关于如何正确转换类型的证据,但从来没有清楚地解释为什么要使用int()和static_cast<int>()从double转换为int。然而,我仍然不清楚static_cast<int>()和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)
}我检查了17.8节,但仍然没有发现这个主题的清晰度。有人能帮帮忙吗?我正在寻找一种将static_cast与函数式转换进行比较的解决方案。
发布于 2018-11-26 06:02:26
显式类型转换是允许的[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.
}https://stackoverflow.com/questions/53472107
复制相似问题