I am pretty new to C++17 and am attempting to understand the decltype
keyword and how it pairs with auto
.
Below is a snippet of code that produces an unexpected result.
#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;
}
Surprisingly, the compiler tells me there is a mismatch in clamp
and that low
and high
are int
. If I change auto
to int16_t
all is good in the world and all the types are int16_t
as expected.
The question I'm posing is, why does auto
cast low
and hi
to int
when all of the types are int16_t
? Is this a good use case for decltype
?
Even after reading cppreference.com, I don't fully understand how decltype
works, so excuse my ignorance.