Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we have to specify data type again after the arrow symbol ( -> )

Tags:

c++

c++11

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);
 }
like image 812
Hariom Singh Avatar asked Jan 03 '23 11:01

Hariom Singh


1 Answers

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.

like image 131
StoryTeller - Unslander Monica Avatar answered Jan 25 '23 22:01

StoryTeller - Unslander Monica