Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why compiler warns about implicit conversion in setprecision?

Tags:

c++

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

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

I'm a little bit confused about this warning since I just try to save the current value of the precision to set it back 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 right way to save the precision value and set it back later in this case?

like image 402
Haldun Avatar asked Jul 27 '12 23:07

Haldun


1 Answers

It looks like it's just an oversight in the standard specification.

ios_base::precision has two overloads, one that gets and one that sets the 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 takes a plain old int:

unspecified-type setprecision(int n);

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

str.precision(n);

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

You can either just call precison() yourself, as above, or assume int is sufficient and cast.

#include <iomanip>
#include <iostream>

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

Edit: Apparently it was submitted to be fixed and reached no concensus (closed as not-a-defect).

like image 86
GManNickG Avatar answered Oct 17 '22 11:10

GManNickG