Portable floating point variable temples

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?


Source: gcc

Leave a Reply