问题描述
所以我问了这个问题,我想通过static_cast解决它.(顺便说一句,它确实解决了问题,我只是不确定我是否理解原因.)
So I asked this question and I was tinkering around with solving it via static_cast. (Incidentally it does solve the problem, I'm just not sure if I understand why.)
在代码中:
vector<int> foo = {0, 42, 0, 42, 0, 42};
replace(begin(foo), end(foo), static_cast<int>(foo.front()), 13);
static_cast 是否只是构造了一个 R 值 int?那和只是调用有什么区别:
Is the static_cast simply constructing an R-Value int? What's the difference between that and just the call:
replace(begin(foo), end(foo), int{foo.front()}, 13);
根据答案 static_cast 确实 似乎构造了一个 R 值 int:http://ideone.com/dVPIhD
As inferred by the answers static_cast does seem to construct an R-Value int: http://ideone.com/dVPIhD
但是这段代码不能在 Visual Studio 2015 上运行.这是编译器错误吗?在这里测试:http://webcompiler.cloudapp.net/
But this code does not work on Visual Studio 2015. Is this a compiler bug? Test here: http://webcompiler.cloudapp.net/
推荐答案
- 是的,它与 - int{...}相同,除非- .front()返回一个需要缩小转换的类型.在这种情况下,- int(...)将是相同的.
- Yes, it is the same as - int{...}, unless- .front()returned a type that required a narrowing conversion. In that case,- int(...)would be identical.
在程序员错误的情况下,静态转换不太可能做一些危险的事情,比如将指针转换为 int 而不是 int(...).
In the case of programmer error, static cast is marginally less likely to do something dangerous, like convert a pointer into an int than int(...).
注意消除强制转换会导致未定义的行为,因为替换操作修改了前面的元素,这可能会破坏 std::replace.
Note eliminating the cast results in undefined behaviour as the front element is modified by the replace operation, and that could break std::replace.
我会用
template<class T>
std::decay_t<T> copy_of(T&& t){return std::forward<T>(t); }
我在这里.
至于为什么这在 MSVC 中不起作用...
As for why this isn't working in MSVC...
MSVC 可以帮助您处理将 T 类型的变量转换为 T 并且什么都不做的情况.这会破坏您的代码.
MSVC helpfully takes situations where you cast a variable of type T to a T and proceeds to do nothing.  This breaks your code.
有一个编译器标志 (/Zc:rvalueCast) 你可以用来让 MSVC 不再破坏你的代码.
There is a compiler flag (/Zc:rvalueCast) you can use to make MSVC no longer break your code.
这篇关于static_cast<T> 是什么?对 T& 做些什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


 大气响应式网络建站服务公司织梦模板
大气响应式网络建站服务公司织梦模板 高端大气html5设计公司网站源码
高端大气html5设计公司网站源码 织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选) 财税代理公司注册代理记账网站织梦模板(带手机端)
财税代理公司注册代理记账网站织梦模板(带手机端) 成人高考自考在职研究生教育机构网站源码(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端) 高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)