auto
can deduce the return type then why do we need trailing arrow symbol (->) to deduce the return type
#include <iostream>
auto add (int i, int j)->int
{
return i+j;
}
int main()
{
int x=10,y=20;
std::cout<<add(x,y);
}
In C++11, there is no return type deduction for functions. auto
is not a placeholder type to be deduced here. You could say its meaning is overloaded.
For functions, auto
simply means the return type will be specified as a trailing return type. You cannot omit the trailing return, or your program will be ill-formed.
This feature was added to the language to allow return type specification to depend on the functions parameters, or enclosing class for members. Those are considered "seen" by the time the trailing return type is reached.
For instance, in this class:
namespace baz {
struct foo {
enum bar {SOMETHING};
bar func();
};
}
If we implement that member function out of line in C++03, it would have to look like this:
baz::foo::bar baz::foo::func() {
return SOMETHING;
}
We must specify the fully qualified name for the return type. Which can quickly become unreadable. But with trailing return types:
auto baz::foo::func() -> bar {
return SOMETHING;
}
The full enclosing namespace is already seen, and bar
can be specified using an unqualified id.
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