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.
我想计算转换因子。为此我必须将最大值除以例如按uchar的最大值ushort。
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.
然而,这是不正确/可能的。
1 个解决方案
#1
3
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;
}
演示
#1
3
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;
}
演示