c++ - 减少 C++ 中的转换困惑

标签 c++ templates casting

在对泛型类进行编程时,我最终得到的方法充满了强制转换(否则我会收到警告,这些警告在我们的项目中被视为错误):

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 中使用了魔法常量。即使我将它们分开,也会增加困惑。无论哪种方式,这都不是问题的重点:)

最佳答案

一个简单的方法是关闭代码周围的警告。使用 MSVC:

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

但是,如果您的魔术常量不需要 double 的扩展精度,则更好的方法是只使用 float 文字。只需将 f 附加到您的浮点文字即可。此外,100 不需要转换。如果您确实需要精确度,那么请回过头来禁用警告。

关于c++ - 减少 C++ 中的转换困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9526076/

相关文章:

java - Swing 绘制在不正确的坐标上

c++ - 从单例类中删除对象

c++ - 仅在 Vim 中为 .h 和 .cpp 文件启用某些插件和选项

c++ - vector 和倾销

c++ - 使用枚举来专门化模板

c++ - 政策和模板

c++ - 如何将数组指针从模板函数转换为数组参数?

c++ - 为什么unique_ptr不允许const_cast?

c++ - 是否可以在类定义之外以某种方式提供相当于 operator bool cast 的东西?

c++ - Visual Studio sizeof 非法操作数