int16_t上的C ++自动转换为整数

Max*_*Max 19 c++ decltype auto c++17

我是C ++ 17的新手,正尝试了解decltype关键字及其与的搭配auto

下面是产生意外结果的代码片段。

#include <typeinfo>
#include <iostream>
#include <algorithm>

using namespace std;

int main() {

  int16_t mid = 4;
  auto low = mid - static_cast<int16_t>(2);
  auto hi = mid + static_cast<int16_t>(2);

  int16_t val;
  cin >> val;

  val = std::clamp(val,low,hi);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,编译器告诉我clampand lowhighare都不匹配int。如果我更改autoint16_t世界上的所有人都很好,并且所有类型都int16_t符合预期。

我提出这个问题时,为什么不autolow,并hiint当所有的类型是int16_t这是一个很好的用例decltype吗?

即使在阅读cppreference.com之后,我仍然不完全了解其decltype工作原理,所以请原谅我的无知。

J. *_*rez 20

问题不在auto这里。当您减去两个int16_t值时,结果为int。我们可以在这里以下代码演示它:

#include <iostream>
#include <cstdint>
using namespace std;

template<class T>
void print_type(T) {
    std::cout << __PRETTY_FUNCTION__ << std::endl; 
}

int main() {
    int16_t a = 10;
    int16_t b = 20;
    print_type(a);
    print_type(b);
    print_type(a - b); 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

ab均为short int,但是当您将它们相加或相减时,会生成一个正则int。这是为了防止溢出/并向后兼容。


Rol*_*lig 5

这种现象称为通常的算术转换。它在C和C ++标准中定义,并且(粗略地说)将小于an的任何内容转换intint。它也转换较大的类型。花一些时间来阅读它,您会经常需要它。