John - 1 year ago 64

C++ Question

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:

- How do I dynamically select the max value?
- 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.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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;
}
```