首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >static_cast<type>()与type ()

static_cast<type>()与type ()
EN

Stack Overflow用户
提问于 2018-11-26 05:21:04
回答 1查看 103关注 0票数 1

在“编程:使用C++的原则和实践”的“8.5.7节参数检查和转换”中,下面的示例是关于如何正确转换类型的证据,但从来没有清楚地解释为什么要使用int()static_cast<int>()double转换为int。然而,我仍然不清楚static_cast<int>()int()的好处。

代码语言:javascript
复制
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与函数式转换进行比较的解决方案。

EN

回答 1

Stack Overflow用户

发布于 2018-11-26 06:02:26

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

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

另一方面,如果你只将它用于基础类型,那就没问题了。不应该在泛型代码中使用它:

代码语言:javascript
复制
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!

如果你想要一个简短而安全的演员阵容,请使用花括号风格:

代码语言:javascript
复制
template<T,class...Args>
auto safe_construct(Args...args){
  return U{args...}; //OK equivalent to a static_cast + narrowing checks.
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53472107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档