c++ - 奇怪的类型推导

标签 c++ integer expression implicit-conversion

今天我看到了一个非常奇怪的类型推导。这是代码:

unsigned int y = 15;
int k = 5;
auto t = k - y / 2;

kint ,我假设 t 的类型应该是 int也。但令我惊讶的是,它的类型是 unsigned int .我找不到为什么类型被推断为 unsigned int .知道为什么吗?

最佳答案

由于通常的算术转换,如果两个操作数具有相同的转换等级并且其中一个操作数具有无符号整数类型,则表达式的类型具有相同的无符号整数类型。

来自 C++ 17 标准(5 个表达式,第 10 页)

— Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.



注意类型unsigned int的转换等级等于 int 类型的等级( signed int )。来自 C++ 17 标准(4.13 整数转换等级,p.#1)

— The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type



下面是一个更有趣的例子。假设有两个声明
unsigned int x = 0;
long y = 0;

并且两种类型的宽度相同且相等,例如 4字节。众所周知,long 类型的等级大于 unsigned int 类型的等级.一个问题出现了什么id表达式的类型
x + y

表达式的类型是 unsigned long .:)

这是一个演示程序,但不是类型 longunsigned int有使用的类型 long longunsigned long .
#include <iostream>
#include <iomanip>
#include <type_traits>

int main() 
{
    unsigned long int x = 0;
    long long int y = 0;

    std::cout << "sizeof( unsigned long ) = " 
              << sizeof( unsigned long )
              << '\n';

    std::cout << "sizeof( long long ) = " 
              << sizeof( long long )
              << '\n';

    std::cout << std::boolalpha 
              << std::is_same<unsigned long long, decltype( x + y )>::value
              << '\n';

    return 0;
}

程序输出是
sizeof( unsigned long ) = 8
sizeof( long long ) = 8
true

那就是表达式 x + y 的类型是 unsigned long long尽管表达式的操作数都没有这种类型。

关于c++ - 奇怪的类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61579749/

相关文章:

c++ - 在 Unreal 4 插件中链接 DLL

c++ - 如何使用 C++ winapi 32 默认显示组合框的第二个值?

java - 如何使用队列对整数流进行排序?实验室JAVA

python - python中字符串float转int

在用 OR 连接的 where 子句中使用动态谓词的 linq 查询

c++ - 是否可以用外部友元 lambda 函数覆盖虚函数?

c++ - std::is_same 在类型相等性检查上的荒谬行为

c++ - 不能使用 push_back 将整数插入 1D/2D vector

c# - 用于比较 string[] 是否包含给定字符串的 lambda 表达式

c++ - 与临时对象一起使用时了解 C++ std::shared_ptr