当编程泛型类,我结束了与石膏堆满方法铸造杂波(否则我得到的警告,被视为错误对我们的项目):降低C++
template <typename floatType>
class foo
{
public:
typedef floatType real_type;
real_type bar()
{
real_type a = (real_type)0.5; // should I be using static_cast? Either way, the code becomes cluttered quickly
real_type b = a + 0.6; // warning here for floatType = float
real_type someLongEquation = a + ((real_type)0.5 * (real_type)100) + (real_type)17.0;
return a + b + someLongEquation;
}
};
int main()
{
{
foo<float> z;
z.bar();
}
{
foo<double> z;
z.bar();
}
return 0;
}
有什么办法减少混乱?
请注意,我知道我在someLongEquation
中使用了魔术常量。即使我把它们分开,也会增加混乱。无论哪种方式,这不是问题:)
什么是你得到的警告? – 2012-03-01 23:57:42
@DavidBrown:'从'double'转换为'float',可能会丢失数据'(在内建类型之间强制转换可能会导致精度损失) – Samaursa 2012-03-02 00:07:44
只需在每个常量值后加上'f'。将float分配到double是可以的;) – nullpotent 2012-03-02 00:13:27