Portable floating point variable templates

瘦欲@ 提交于 2019-12-11 10:47:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!