2012-03-01 85 views
2

当编程泛型类,我结束了与石膏堆满方法铸造杂波(否则我得到的警告,被视为错误对我们的项目):降低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中使用了魔术常量。即使我把它们分开,也会增加混乱。无论哪种方式,这不是问题:)

+0

什么是你得到的警告? – 2012-03-01 23:57:42

+0

@DavidBrown:'从'double'转换为'float',可能会丢失数据'(在内建类型之间强制转换可能会导致精度损失) – Samaursa 2012-03-02 00:07:44

+0

只需在每个常量值后加上'f'。将float分配到double是可以的;) – nullpotent 2012-03-02 00:13:27

回答

0

一个简单的方法是只关闭周围的代码的预警点。随着MSVC:

#pragma warning(push) // save warnings state 
#pragma warning(disable:4244) // narrowing conversion 
// code here ... 
#pragma warning(pop) // restore warnings 

更好的方法,但是,这是只使用float文字,如果你不需要的double的扩展精度为你的魔术常量。只需附加一个f到您的浮点文字,你会没事的。另外,100不需要演员。如果你确实需要精确度,那么退回到禁用警告。

0

你应该在魔术常量分离出来,并将其存储在正确的泛型类型。所有的演员将被限制在那个位置。现在(我认为)C++ 11允许在非整型常量静态的类初始化中很容易。

template <typename floatType> 
class foo 
{ 
public: 
    typedef floatType real_type; 

    static constexpr real_type A = real_type(0.5); 
    static constexpr real_type B = real_type(0.6); 
    static constexpr real_type C = real_type(100.0); 
    static constexpr real_type D = real_type(17.0); 

    real_type bar() 
    { 
    real_type a = A; 
    real_type b = a + B; 

    real_type someLongEquation = a + (A * C) + D; 

    return a + b + someLongEquation; 
    } 
}; 
+0

IIRC,C++ 11只允许非静态成员。 – Xeo 2012-03-14 07:27:57

+0

@Xeo之前我无法找到参考,但现在我已经有了。静态constexpr数据成员可以在课堂上初始化,如果他们有'文字类型',其中包括'浮动'。 [class.static.data]§9.4.2/ 3 – bames53 2012-03-14 16:05:58

+0

啊,是的,我忽略了'constexpr'。 :) – Xeo 2012-03-14 17:43:11