In C++20, we are now able to constrain the auto
keyword to only be of a specific type. So if I had some code that looked like the following without any constraints:
auto something(){
return 1;
}
int main(){
const auto x = something();
return x;
}
The variable x
here is deduced to be an int
. However, with the introduction of C++20, we can now constrain the auto
to be a certain type like this:
std::integral auto something(){
return 0;
}
int main(){
const auto x = something();
return x;
}
Doesn't this defeat the purpose of auto
here? If I really need a std::integral
datatype, couldn't I just omit the auto
completely? Am I misunderstanding the use of auto
completely?
std::integral
isn't a type, it's a concept. The second version of the code is simply promising that whatever typesomething()
returns, it will be a type that satisfies the conceptstd::integral
.