【发布时间】:2010-08-02 11:53:03
【问题描述】:
我有以下代码:
template<typename I,typename O> O convertRatio(I input,
I inpMinLevel = std::numeric_limits<I>::min(),
I inpMaxLevel = std::numeric_limits<I>::max(),
O outMinLevel = std::numeric_limits<O>::min(),
O outMaxLevel = std::numeric_limits<O>::max() )
{
double inpRange = abs(double(inpMaxLevel - inpMinLevel));
double outRange = abs(double(outMaxLevel - outMinLevel));
double level = double(input)/inpRange;
return O(outRange*level);
}
用法是这样的:
int value = convertRatio<float,int,-1.0f,1.0f>(0.5);
//value is around 1073741823 ( a quarter range of signed int)
问题在于 I=int 和 O=float 带有函数默认参数:
float value = convertRatio<int,float>(123456);
double(inpMaxLevel - inpMinLevel) 行的结果是 -1.0,我希望它是浮点数 4294967295。
你有什么想法可以做得更好吗? 基本思想只是将一个范围内的值转换为具有不同数据类型可能性的另一个范围。
【问题讨论】:
-
如果我没记错的话
numeric_limits<int>::min()和numeric_limits<float>::min()的含义完全不同:对于浮点,它是最小的非零正值。我不明白如何将这两者混合并获得有意义的东西。 -
是的,如果 T 是浮点数,那么用户应该覆盖默认值
标签: c++ templates math numeric