在用作模板放慢参数的一类的成员函数,我有包含以下代码的函数:奇怪静态铸造行为用作模板参数
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写的。 – Grzegorz
@j_random_hacker Nope,'+'的优先级高于'<<'的优先级,请参见[here](http://en.cppreference.com/w/cpp/language/operator_precedence)。 –
@j_random_hacker:'1 << 2 + 1'确实是'1 << 3',例如'8',而不是'3'。 “... <<(cond)”的优先顺序是有意义的吗? x:y << ...在这种情况下代替'y',表达式将使用'y << ...'。 – Grzegorz