Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a value constant that depends on the template type

I would like to create a C++ template function which has different constants that get used in the implementation depending on the choice of the template type.

#define FLOAT_EPSILON       (0.000001f)
#define DOUBLE_EPSILON      (0.00000000000001)

template <class T> void func(T params)
{
    const T epsilon = ???? // either FLOAT_EPSILON or DOUBLE_EPSILON depending on T
    // do some calculations using epsilon
}

template void func(float params);
template void func(double params);

I can't quite work out how to do this best, although I thought of some half-assed ways that work. Can you help?

like image 563
Robotbugs Avatar asked Dec 13 '25 13:12

Robotbugs


1 Answers

You can use a helper template to choose the epsilon.

template <typename T> struct EpsilonChooser;

template <> struct EpsilonChooser<float>
{
    float const value = 0.000001f;
};

template <> struct EpsilonChooser<double>
{
    double const value = 0.00000000000001;
};

template <class T> void func(T params)
{
    const T epsilon = EpsilonChooser<T>::value;
    // do some calculations using epsilon
}
like image 58
R Sahu Avatar answered Dec 16 '25 08:12

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!