我有以下代码:
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。
你有什么想法可以做得更好吗?基本思想只是将一个范围内的值转换为具有不同数据类型可能性的另一个范围。