int16_t 上的 C++ 自动转换为整数
C++ auto on int16_t casts to integer
我是 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;
}
令人惊讶的是,编译器告诉我 clamp
不匹配,low
和 high
是 int
。如果我将 auto
更改为 int16_t
世界上一切都很好并且所有类型都如预期的那样 int16_t
。
我提出的问题是,为什么当所有类型都是 int16_t
? 这是 decltype
?
的一个很好的用例吗
即使看了cppreference.com,我也没有完全理解decltype
是如何工作的,请原谅我的无知。
这里的 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 int
,但是当您添加或减去它们时,它会生成一个常规的 int
。这是为了防止溢出 / 也是为了向后兼容。
这种现象称为。它在 C 和 C++ 标准中定义,并且(粗略地说)将任何小于 int
的东西转换为 int
。它也可以转换更大的类型。花点时间阅读一下,你会经常需要它。
我是 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;
}
令人惊讶的是,编译器告诉我 clamp
不匹配,low
和 high
是 int
。如果我将 auto
更改为 int16_t
世界上一切都很好并且所有类型都如预期的那样 int16_t
。
我提出的问题是,为什么当所有类型都是 int16_t
? 这是 decltype
?
即使看了cppreference.com,我也没有完全理解decltype
是如何工作的,请原谅我的无知。
这里的 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 int
,但是当您添加或减去它们时,它会生成一个常规的 int
。这是为了防止溢出 / 也是为了向后兼容。
这种现象称为int
的东西转换为 int
。它也可以转换更大的类型。花点时间阅读一下,你会经常需要它。