【问题标题】:Strange static cast behaviour in a member function of class used as template parameter用作模板参数的类的成员函数中的奇怪静态转换行为
【发布时间】:2013-11-09 00:42:14
【问题描述】:

在用作模板参数的类的成员函数中,我有一个包含以下代码的函数:

double x = /*Something operation returning double*/;
x /= CubeWidth; /*CubeWidth is a class member*/
cout << "Element after centering and normalization = " << x << endl;
cout << "and after adding 1 and truncating = " << x+1 << endl;
cout << "then static cast = " << (int) x+1 << endl;

这个函数的输出是

Element after centering and normalization = 1
and after adding 1 and truncating = 2
then static cast = 1

显然,最后一行应该给出答案 2。

如果我实例化完全相同的类而不使用它作为模板参数,我不会得到这个打印输出,而是我有正确的。

谁能告诉我为什么会这样?

【问题讨论】:

  • 好问题为什么。不过,我知道如何解决这个问题 - 将您的表达式放在括号中。例如((int)x+1)。我也将等待好的解释。编辑:如果这个解决方案不起作用,那么我 一定是 Daniel Frey 写的。
  • @j_random_hacker 不,+ 的优先级高于&lt;&lt;,见here
  • @j_random_hacker: 1 &lt;&lt; 2 + 1 真的是1 &lt;&lt; 3 例如8,而不是3。对于... &lt;&lt; ( cond ) ? x : y &lt;&lt; ...,优先级是有意义的,因为在这种情况下,表达式将使用y &lt;&lt; ...,而不是y
  • 你说的不是截断,而是你和演员一起。
  • @DanielFrey:哎呀,&lt;&lt;+ 的关系是对的。但我对具有更高优先级的类型转换并因此被等效解析为((int) x) + 1 是正确的,这可能不是 OP 想要做的,即使它没有产生明显的差异。您在回答中提到的舍入问题会导致可观察到的错误。

标签: c++ templates casting member-functions


【解决方案1】:

很可能x(双精度)不完全是1,而是0.9999999...。通过打印x==1.0x&lt;1.0 检查它的确切值,看看什么是真的。或者在输出中添加更多数字:

cout << "and after adding 1 and truncating = " << setprecision( 15 ) << x+1 << endl;

四舍五入将舍弃逗号后的所有数字,因此1.999999... 变为1

【讨论】:

  • 我觉得你是对的,但是效果已经开始随机出现了。我只是再次运行测试,根本没有改变任何东西,只是我不再连接到 wifi!这可能有关系吗?我知道我正在抓住稻草......
  • @Plamen Cosmic ray, "relative Mondfeuchtigkeit", ... - 但最终更可能是您未显示的 x 的计算。无论如何,只要让你的代码更安全,添加更多数字或允许一个小的增量,例如(int)(x+1.000001)。也许this page 会有所帮助。
猜你喜欢
  • 2011-03-14
  • 1970-01-01
  • 2016-06-10
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多