Why does the compiler warn about implicit conversion to setprecision?

When I compile the following code, the compiler gives me a warning:

"Implicit conversion loses integer precision: 'std::streamsize' (aka 'long') to 'int'". 

I am a little confused about this warning, as I will just try to keep the current accuracy value in order to return it to the original value later.

 #include <iomanip> #include <iostream> int main() { std::streamsize prec = std::cout.precision(); std::cout << std::setprecision(prec); } 

What is the correct way to save the accuracy value and set it later in this case?

+6
source share
1 answer

It seems like this is just an oversight in the standard specification.

ios_base::precision has two overloads: one that receives, and one that sets precision:

 // returns current precision streamsize precision() const; // sets current precision and returns old value streamsize precision(streamsize prec) const; 

So this code will not give you warnings:

 #include <iostream> int main() { std::streamsize prec = std::cout.precision(); // gets std::cout.precision(prec); // sets } 

However, the setprecision() function simply accepts a simple old int :

 unspecified-type setprecision(int n); 

and returns an unspecified functor, which when consumed by the str stream has the effect:

 str.precision(n); 

In your case, streamsize not int (and does not have to be), so this is a warning. The standard should probably be changed so that the setprecision parameter setprecision not int , but streamsize .

You can simply call precison() yourself, as above, or assume that int is sufficient and excellent.

 #include <iomanip> #include <iostream> int main() { std::streamsize prec = std::cout.precision(); std::cout << std::setprecision(static_cast<int>(prec)); } 

Edit: Apparently, it was fixed and no consensus was reached (closed as a non-defect) .

+7
source

Source: https://habr.com/ru/post/921534/


All Articles