Reputation: 4387
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?
Upvotes: 3
Views: 709
Reputation: 8824
The R-Sahu solution will transform to a variable template in C++14, demo here :
template <typename T> constexpr T epsilon;
template <> constexpr float epsilon<float> = 0.001f;
template <> constexpr double epsilon<double> = 0.000001;
Upvotes: 3
Reputation: 206557
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
}
Upvotes: 4