![](/img/trans.png)
[英]C++ Warning C4244 'return': conversion from 'double' to 'int', possible loss of data Visual Studio 2015
[英]How to disable Visual Studio warning C4244 for std::vector copy or assign with implicit narrowing conversion
我想将双精度向量转换为浮点向量。 而且我不希望 Visual Studio 抛出警告 C4244,“可能丢失数据”,即缩小转换。
请不要发表评论或回答说我不应该这样做。 我知道后果。 我只是想抑制警告。 在此特定功能范围之外禁用警告是不可接受的,例如通过项目设置全局禁用。
我也想使用 vector::copy 或 vector::assign。 使用 static_cast<> 避免通过 transform() 或 for_each() 发出警告是......对我的口味来说太明确了。 所以这个问题是如何禁用警告,而不是避免它。
我的警告抑制尝试不起作用:
vector<float> DoubleVectorToFloat( vector<double> & x ){
#pragma warning( push )
#pragma warning( disable : 4244 )
return vector<float>( x.begin(), x.end() );
#pragma warning( pop )
}
我知道禁用警告是不好的。 但一种尺寸并不适合所有人。 我的库是实时的,处理速度为 10's MiB/s。 我想要调用模板 _Copy_unchecked1(etc); 我不想支付错误检查的性能损失。
改用这个:
std::vector<float> DoubleVectorToFloat(const std::vector<double>& x)
{
std::vector<float> r;
r.reserve(x.size());
std::transform(x.begin(), x.end(), std::back_inserter(r),
[](double a) { return static_cast<float>(a); });
return r;
}
std::transform
是将一种类型的向量转换为另一种类型的向量的正确方法。
我强烈建议使用这种方法,而不是使用向量构造函数并消除警告。
要禁用此类警告,您可能必须将此函数放入其自己的模块中并禁用顶部的警告:
// top-of-file
#pragma warning( disable : 4244 )
// All your includes here
std::vector<float> DoubleVectorToFloat( std::vector<double> & x ){
return std::vector<float>( x.begin(), x.end() );
}
// end-of-file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.