Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't constraining the "auto" in C++ defeat the purpose of it?

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?

like image 754
beep_boop Avatar asked Nov 01 '21 18:11

beep_boop


2 Answers

A constraint on the deduced auto type doesn't mean it needs to be a specific type, it means it needs to be one of a set of types that satisfy the constraint. Note that a constraint and a type are not the same thing, and they're not interchangeable.

e.g. a concept like std::integral constrains the deduced type to be an integral type, such as int or long, but not float, or std::string.

If I really need a std::integral datatype, couldn't I just omit the auto completely?

In principle, I suppose you could, but this would at the minimum lead to parsing difficulties. e.g. in a declaration like

foo f = // ... 

is foo a type, or a constraint on the type?

Whereas in the current syntax, we have

foo auto f = // ... 

and there's no doubt that foo is a constraint on the type of f.

like image 114
cigien Avatar answered Sep 19 '22 06:09

cigien


If I really need a std::integral datatype, couldn't I just omit the auto completely?

No, because std::integral is not a type, it's a concept, a constraint on types (or if you will, a set of types rather than a single type).

Doesn't this defeat the purpose of auto here?

The original purpose of auto in C++11 is telling the compiler: Whatever type you deduce.*

With C++20, auto has an expanded use case - together with a concept, a constraint over types. auto still tells the compiler: Whatever type you deduce - but the deduction must also respect the constraint.

* - ignoring issues like constness, l/rvalue reference etc.

like image 32
einpoklum Avatar answered Sep 22 '22 06:09

einpoklum