In my code, I have a lot of template algorithms where the template type must be a floating point (float
, double
, or long double
). Some of these algorithms require a default epsilon value. Example:
template <typename FloatType>
bool approx(FloatType x1, FloatType x2)
{
const FloatType epsilon; // How can I set it ?
return abs(x2 - x1) < epsilon;
}
How can I define it ? I tried the following, it's accepted by gcc, but it's not standard (and not valid in C++11). I know it's possible in C++11, but I have to be compatible with c++03.
template <typename FloatType>
struct default_epsilon
{};
template <>
struct default_epsilon<float>
{
static const float value = 1.0e-05f;
};
template <>
struct default_epsilon<double>
{
static const double value = 1.0e-10;
};
template <>
struct default_epsilon<long double>
{
static const long double value = 1.0e-12l;
};
// Then, I use it like that :
template <typename FloatType>
bool approx(FloatType x1, FloatType x2)
{
return abs(x2 - x1) < default_epsilon<FloatType>::value;
}
// or that
bool approx(FloatType x1, FloatType x2, FloatType epsilon = default_epsilon<FloatType>::value)
{
return abs(x2 - x1) < epsilon;
}