High precision constants for templates

I am writing a template class that takes a floating point type (float, double, decimal, GMP) as a parameter. However, my class requires different numeric constants. Some of them are rational numbers (int / int), while others are irrational and are available for 30 or more decimal places.

What is the best way to initialize these constants, so:

T c1 = <constant>;

      

where is T a template type?

While I could always fall back on doubles (T c1 = 0.1415926535 ...) and rely on the compiler / implicit initializer to convert to the appropriate type, I would like to preserve the extra precision, if at all possible.

I am interested in both the current solutions and those that C ++ 0x (or is it C ++ 1x?) Can result in a table.

+2


a source to share


2 answers


I think the easiest way to do this is to create a specialized container class containing constants, something like this:

template<class T>
class Constants
{
public:
    static const T pi = T(3.1415);
};

//Example specialization:
template<>
class Constants<double>
{
public:
    static const double pi = 3.1415926535897932384626433832795;
};

      

In your real class, you can do something like this:



const T c1 = Constants<T>::pi;

      

This avoids the fact that you have to write complete specialization classes just to override these constants.

Note that the default behavior may revert to implicit double assignment.

+2


a source


Simple and idea, I would overload the type for each of your custom constants:

template<typename T>
struct PI { operator double() { return 3.145243; }

template<>
struct PI<float> { operator float() { return 3.14f; }

template<>
struct PI<int> { operator int() { return 3; }

...

      



Then use

T result = 2*PI<T>();

      

0


a source







All Articles