what is -> in c++ in a function declaration

c++, c++11, decltype, syntax

Solution

This uses trailing return type notation. This:

auto f() -> T { ... }

Is equivalent to this:

T f() { ... }

The advantage is that with a trailing return type notation you can express the type of a function based on expressions that involve the arguments, which is not possible with the classical notation. For instance, this would be illegal:

    template <class T>
    decltype(foo(t)) transparent_forwarder(T& t) {
//  ^^^^^^^^^^^^^^^^
//  Error! "t" is not in scope here...

        return foo(t);
    }

Concerning your edit:

Based on the above: What is wrong here?

template <typename T1, typename T2>
auto sum(T1 v1, T2 v2) -> decltype(v1 + v2) {
    return v1 + v2;
}

Nothing.

Concerning your second edit:

[...] It is using decltype without the need for -> in the function declaration. So Why do we need ->

In this case you don't need it. However, the notation that does use trailing return type is much clearer, so one may prefer it to make the code easier to understand.

Problem

In the Wikipedia article on `decltype` http://en.wikipedia.org/wiki/Decltype I came across this example: ``` int& foo(int& i); float foo(float& f); template <class T> auto transparent_forwarder(T& t) −> decltype(foo(t)) { return foo(t); } ``` Though I understood the motive behind this function, I didnot understand the syntax it uses and specifically the `->` in the declaration. What is -> and how is it interpreted? EDIT 1 Based on the above: What is wrong here? ``` template <typename T1, typename T2> auto sum(T1 v1, T2 v2) -> decltype(v1 + v2) { return v1 + v2; } ``` The error is: ``` error: expected type-specifier before ‘decltype’ error: expected initializer before ‘decltype ``` Answer to EDIT 1: OOPS! I forgot to use `-std=c++11` compiler option in g++. EDIT 2 Based on the below answer. I have a related question: Look at the declaration below: ``` template <typename T1, typename T2> decltype(*(T1 *) nullptr + *(T2 *) nullptr) sum2(T1 v1, T2 v2); ``` It is using `decltype` without the need for `->` in the function declaration. So Why do we need `->`

Original source

Related problems