【问题标题】:static_cast<type>() vs type () [duplicate]static_cast<type>() 与 type () [重复]
【发布时间】:2018-11-25 21:21:04
【问题描述】:

在“编程:使用 C++ 的原则和实践”中,“第 8.5.7 节参数检查和转换”中给出了以下示例作为如何正确转换类型的证据,但从未明确解释您为什么要使用 int()static_cast&lt;int&gt;() 相比,从double 转换为int。但是,我仍然不清楚 static_cast&lt;int&gt;()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 与函数样式转换进行比较的解决方案。

【问题讨论】:

  • @cbuchart 答案不包括功能符号转换。

标签: c++ type-conversion explicit-conversion


【解决方案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.
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    相关资源
    最近更新 更多