Vladimir Prus


vladimirprus.com

Friday, March 18, 2005

Outputting T

I'm positively shocked. In C++, there's no easy way to write a template function with one parameter that will output that parameter to a stream, with full precision.

If you write:

std::cout << t;
then you'll be using the default stream precision, which is 6. And 't' can be double with 10 digits after the dot.

If you write:

std::cout << setprecision(10000) << t;
you'll suddenly get too many digits. For outputting "1.1", you'll get:
1.100000000000000088817841970012523233890533447265625
even though real precision of double is 15-16 digits.

If you write:

std::cout << setprecision(fancy_formula_involving(numeric_limits<T>::digits) << t;
the code won't compile if T is "char[N]". And if numeric_limits is not specialized for a given T, results can also be strange.

Oops!

No comments: