便携式浮点变量模板 [英] Portable floating point variable templates
问题描述
如何在c ++ 14中定义便携式高精度浮点变量模板?以下程序应使用 double
和 long double
精度打印pi。
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;
}
$ b < std = c ++ 14 我得到
3.1415926535897931
3.141592653589793116
我的猜测是gcc将数字转换为double,然后应用模板。我不认为 L
文字是答案,因为我不想重写,当我移动到float128或更高。如何使编译器保留所有精度?
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?
推荐答案
除非另有说明,否则所有浮点文字的类型为 double
。你使用它作为 T
(无论 T
可能)的初始化器无关紧要,将 double
转换为 T
初始化 。
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
.
使用 l
后缀字面,使其成为 long double
,然后转换为 T
。
Suffix the literal with l
to make it a long double
, which is then converted to T
.
这篇关于便携式浮点变量模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!