c++ - 用作模板参数的类的成员函数中的奇怪静态转换行为

标签 c++ templates casting member-functions

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

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。

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

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

最佳答案

最有可能 x (a double) 不完全是 1 , 它是 0.9999999... .通过打印 x==1.0 检查它的确切值或 x<1.0看看什么是真的。或者在输出中添加更多数字:

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

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

关于c++ - 用作模板参数的类的成员函数中的奇怪静态转换行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19665358/

相关文章:

azure - JSON 对象作为 ARM 模板函数参数

c - 转换时使用内存? [C]

c++ - 为什么 reinterpret_cast 在危险时仍在使用

c++ - 为什么对 NULL 指针的函数调用在 C++ 中有效?

C++11 - 模板 std::enable_if 和 std::result_of

尽管格式有效,MySQL str_to_date 仍生成 NULL

c++ - 从 int 到 enum 类类型的转换可能吗?

c++ - 使用 boost Spirit 解析为 STL vector

C++/CX 如何将 IRandomAccessStream^ 转换为字节并返回。 (UWP)

c++ - 如何重写模板函数来处理类型推导