问题
How to define portable high-precision floating point variable templates in c++14? The program below should print pi with double and long double precision.
#include <iostream>
#include <iomanip>
#include <limits>
template<typename T>
constexpr T pi = T(3.141592653589793238462643383279502884197);
int main() {
std::cout << std::setprecision(std::numeric_limits<double>::max_digits10) << pi<double> << std::endl;
std::cout << std::setprecision(std::numeric_limits<long double>::max_digits10) << pi<long double> << std::endl;
}
When I compile with GCC 5.1.0 g++ -std=c++14 I get
3.1415926535897931
3.141592653589793116
My guess is that gcc converts the number to a double and then applies the template. I don't think the L literal is the answer because I don't want to rewrite when I move to float128 or higher. How can I make the compiler retain all the precision?
回答1:
All floating point literals, unless otherwise suffixed, are of type double. That you use it as an initializer for T (whatever T may be) doesn't matter, you're still going to initialize pi with a double converted to a T.
Suffix the literal with l to make it a long double, which is then converted to T.
来源:https://stackoverflow.com/questions/31695041/portable-floating-point-variable-templates