Search code examples
c++templatesnumeric-limits

Using numeric_limits to default parameter values


I have a template statistics class that has range parameters.

template <typename T>
class limitStats
{
public:
    limitStats(T mx, T min) :
      max(mx),
      min(mn),
      range(mx-mn)
    {;}

private:
    const T max;
    const T min;
    const T range;
}

I would like to put default values of maximum and minimum allowable values, but the minimum value is not the same for floating point and integer types.

Normally I can write

T min_val = numeric_limits<T>::isinteger ? numeric_limits<T>::min() : -numeric_limits<T>::max();

I have found that I can't use it as a default parameter

limitStats(T mx = std::numeric_limts<T>::max(), 
           T mn = numeric_limits<T>::isinteger ? numeric_limits<T>::min() : -numeric_limits<T>::max())

Is there a way of achieving something like this?


Solution

  • You might want to rethink your design. What are you trying to do with your limitStats that std::numeric_limits doesn't provide?

    Don't replicate the badness of the design of std::numeric_limits. For example, std::numeric_limits<double>::min() is terribly misnamed. The minimum double is the additive inverse of the maximum double. std::numeric_limits is an abuse of notation and an abuse of templates. In my opinion, of course.

    Your idea for min is ill-formed. Think about your default with respect to limitStats<unsigned int>.

    With the defaults, your range is invalid for signed integers. For unsigned ints it replicates max, assuming you fix the problem with limitStats<unsigned int>::min. For floating point types, it is either invalid or replicates max, depending on what you mean by limitStats<floating_point_type>::min.

    Does it even make sense to allow default values? You wouldn't even have this question if you simply don't provide defaults and make the default constructor private/unimplemented.