John John - 2 months ago 8
C++ Question

How can I (safely) divide a maximum value, resulting in a floating point value?

I want to calculate conversion factors. For this I have to divide the maximum value of e.g. ushort by the maximum value of uchar.

I want to do this dynamically, by passing a parameter into a function or a typename. Then I want to select the max values and perform the calculation.

There are two problems:

  1. How do I dynamically select the max value?

  2. How can I safely divide the two values?

All values are known to fit into the range of double.

Ideally I would want to do something like:

double x = numeric_limits<T>::max / numeric_limits<T2>::max;

However that is not correct/possible.


Your proposed idea should work:

#include <iostream>
#include <limits>

template <typename T, typename T2>
double get_ratio()
    return static_cast<double>(std::numeric_limits<T>::max()) / std::numeric_limits<T2>::max();

int main()
    auto ratio = get_ratio<unsigned short, unsigned char>();
    std::cout << ratio << '\n';
    return 0;