I want to perform a narrowing conversion of a vector of doubles to a vector of floats. And I do not want Visual Studio throwing warning C4244, "possible loss of data", i.e. narrowing conversion.
Please do not post comments or answers saying I should not do this. I am aware of the consequences. I just want to suppress the warning. It is not acceptable to disable the warning outside the scope of this specific function, e.g. globally via project settings.
I also want to use either vector::copy or vector::assign. Avoiding the warning via transform() or for_each() with static_cast<> is.... just too explicit for my tastes. So this questions is how to disable the warning, not avoid it.
My attempt at warning suppression does not work:
vector<float> DoubleVectorToFloat( vector<double> & x ){
#pragma warning( push )
#pragma warning( disable : 4244 )
return vector<float>( x.begin(), x.end() );
#pragma warning( pop )
}
I understand that disabling warnings is bad. But one size does not fit all. My library is real-time, and processes 10's MiB/s. I want template _Copy_unchecked1(etc) to be called; I do not want to pay the performance penalty of error checks.
To disable this type of warning you may have to put this function into a module of its own and disable the warning at the top:
// 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
Use this instead:
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
is the correct way to transform a vector of a type to a vector of another type.
I am strongly suggesting this approach as opposed to using the vector constructor and silencing the warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With