You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何unsigned short按位异或结果为signed int?编译报错解析

为什么unsigned short异或后调用std::bit_width会编译失败?

问题重现

可正常运行的代码

#include <bit>
#include <iostream>

int main()
{
    unsigned int x = 31;
    unsigned int y = 73;
    std::cout << std::bit_width(x ^ y);
}

运行结果:7

无法编译的代码

#include <bit>
#include <iostream>

int main()
{
    unsigned short x = 31;
    unsigned short y = 73;
    std::cout << std::bit_width(x ^ y);
}

编译报错:

E0304 no instance of function template "std::bit_width" matches the argument list
'std::bit_width': no matching overloaded function found

环境:Windows + MSVC + Visual Studio 2022

原因解析

核心问题在于C++的整数提升规则和std::bit_width的重载限制:

  1. 整数提升(Integral Promotion):当unsigned short这类窄整数类型参与算术运算(比如异或^)时,会被自动提升为int类型(Windows上int是32位,完全能容纳16位unsigned short的所有取值范围)。因此x ^ y的结果类型是int,而非unsigned short。
  2. std::bit_width的重载限制:std::bit_width是C++20引入的函数模板,仅针对无符号整数类型提供重载(包括unsigned char、unsigned short、unsigned int等),不支持带符号的int类型。当传入int类型的异或结果时,编译器找不到匹配的重载,自然编译失败。

而unsigned int类型在异或运算后结果仍为unsigned int,正好匹配std::bit_width的重载,所以能正常运行。

验证方式

可以通过typeid查看运算结果的类型,代码如下:

#include <bit>
#include <iostream>
#include <typeinfo>

int main()
{
    unsigned short x = 31;
    unsigned short y = 73;
    std::cout << typeid(x ^ y).name(); // MSVC下输出int
}

解决方法

通过显式类型转换,将异或结果转换回无符号短整数类型即可:

#include <bit>
#include <iostream>

int main()
{
    unsigned short x = 31;
    unsigned short y = 73;
    std::cout << std::bit_width(static_cast<unsigned short>(x ^ y));
}

或者直接使用unsigned int类型的变量,从根源避免整数提升带来的类型变化。

内容的提问来源于stack exchange,提问作者Todd Sierens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 18:32:17