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 low和highare都不匹配int。如果我更改auto为int16_t世界上的所有人都很好,并且所有类型都int16_t符合预期。
我提出这个问题时,为什么不auto投low,并hi于int当所有的类型是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)
a和b均为short int,但是当您将它们相加或相减时,会生成一个正则int。这是为了防止溢出/并向后兼容。