【问题标题】:C++ auto on int16_t casts to integerC++ auto on int16_t 强制转换为整数
【发布时间】:2019-09-02 19:07:31
【问题描述】:

我是 C++17 的新手,我正在尝试理解 decltype 关键字以及它如何与 auto 配对。

下面是一段产生意外结果的sn-p代码。

#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;
}

令人惊讶的是,编译器告诉我clamp 不匹配,而low 和high 是int。如果我将auto 更改为int16_t,世界上一切都很好,所有类型都是int16_t,正如预期的那样。

我提出的问题是,当所有类型都是int16_t 时,为什么auto 将low 和hi 转换为int? 这是一个很好的用途decltype 的情况?

即使在阅读 cppreference.com 之后,我也无法完全理解 decltype 的工作原理,请原谅我的无知。

【问题讨论】:

标签: c++ c++17 auto decltype


【解决方案1】:

问题不在于auto。当您减去两个int16_t 值时,结果是int。我们可以用this code here来演示:

#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;
}

a 和 b 都是 short ints,但是当你添加或减去它们时,它会产生一个常规的 int。这是为了防止溢出 / 也是为了向后兼容。

【讨论】:

    【解决方案2】:

    这种现象称为usual arithmetic conversions。它在 C 和 C++ 标准中定义,并且(粗略地说)将小于 int 的任何内容转换为 int。它也转换更大的类型。花点时间阅读一下,您会经常需要它。

    【讨论】:

      猜你喜欢
      • 2018-09-07
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      相关资源
      最近更新 更多