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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With