游戏开发者联盟

c++是不是分别对 char short int long 做了位运算定义?

有点疑惑,就写了点代码测试一下:

void test() {
  char a = 1;
  if (std::is_same<decltype(a >> 1), char>::value)
    std::cout << "type (char>>1) == char" << std::endl;
  if (std::is_same<decltype(a >> 1), int>::value)
    std::cout << "type (char>>1) == int" << std::endl;

  long b = 1;
  if (std::is_same<decltype(b >> 1), long>::value)
    std::cout << "type (long>>1) == long" << std::endl;
  if (std::is_same<decltype(b >> 1), int>::value)
    std::cout << "type (long>>1) == int" << std::endl;

  if (std::is_same<decltype(a + 1), char>::value)
    std::cout << "type (char+1) == char" << std::endl;
  if (std::is_same<decltype(a + 1), int>::value)
    std::cout << "type (char+1) == int" << std::endl;
}

运行结果:

type (char>>1) == int
type (long>>1) == long
type (char+1) == int

看来运算基本就是围绕int 和 long进行的,别的类型先隐式转换到int long,再进行计算。