From this question, it is clear that auto
cannot be used as function argument. My question is why return type is allowed as auto
but function arguments are not ?
auto function(auto data)
{
//DOES something
}
Since, there are many benefits of auto
coming in c++1z, then why not this ?
This syntax was proposed in the Concepts TS, which did not make it into C++17 for various reasons.
Despite some critique I've outlined below, it has been added in C++20.
Note: the following part of the answer has been made obsolete by merging P1141R2 into the standard. I'll leave it here for reference.
However, even if we finally get Concepts in the next iteration (probably C++20), it is not clear the desired syntax will make it into the standard. In this paper, Richard Smith and James Dennett critique the so called "Terse template notations", saying
The Concepts TS introduces too many syntaxes for a function template declaration. Some of those syntaxes have no clear, consistent syntactic marker for templates, which is important semantic information for the reader of the code (remembering that code is read vastly more than it is written).
They go on to propose a different syntax to achieve the goal, while keeping template declarations more consistent:
=> Require an explicit sigil to declare a function to be a template
Replace
void f(auto a) {} template<typename T> void g(auto a) {}
with
template<...> void f(auto a) {} template<typename T, ...> void g(auto a) {}
The ... sigil in the template-parameter-list indicates that additional template parameters will be inferred from the declaration.
So Tl;dr: There are a bunch of reasons related to the standardization procedure why we don't have it in C++17, and there are more reasons why we probably won't ever get it. If I understood the paper correctly, the key point being that every template should be introduced with a template
keyword.
There is already an exhaustive answer, I just want to add my two cents by giving a more handwavy answer....
In general auto
does not stand for "this could be any type" but it just means that the compiler can deduce the type. Thus the two auto
s in
auto function(auto data) {
//...
return x;
}
are quite different. Seeing this definition alone, the compiler can deduce the return type. On the other hand the auto
on the parameter cannot be deduced unless the compiler sees how function
is called. Moreover, there need to be different versions of function
. While it is almost trivial to figure out the type of x
, making the second auto
work requires to turn function
into a template which requires new rules and inevitably introduces new quirks to the language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With