Freddie Witherden
Freddie Witherden

Reputation: 2426

High Precision Constants for Templated Code

I am writing a template class which takes a floating-point-like type (float, double, decimal, GMP) as a parameter. However, my class requires various numeric constants. Some of these are rational numbers (int/int) while others are irrational and available to 30 or so decimal places.

What is the best way to go about initialising these constants, so:

T c1 = <constant>;

where T is the templated type?

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

I am interested in both current solutions and those which C++0x (or is it C++1x?) might bring to the table.

Upvotes: 2

Views: 188

Answers (2)

Inverse
Inverse

Reputation: 4476

Just and idea, I would overload the type for each of your special 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>();

Upvotes: 0

KillianDS
KillianDS

Reputation: 17186

I think the easiest way to do this is to create a specialized container class that holds the 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 then do something like this:

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

This avoid that you have to write complete specialization classes only to redefine those constants.

Note that default behavior can fall back to implicit double assignment.

Upvotes: 2

Related Questions