What is “->” after function declaration?

It’s the new function declaration syntax from C++11, and it’s called the “trailing return type”. At the end of a function declaration, -> means that the following is the return type of the function. It can only be used when the auto keyword is used instead of an actual return type where you would normally expect it.

For instance, these two declarations are compatible:

int foo();
auto foo() -> int;

Depending on your tastes, you may find it prettier than the old declaration syntax, especially when the return type is extremely long/complex:

task<typename details::_TaskTypeFromParam<_Ty>::_Type> create_task(_Ty _Param);
auto create_task(_Ty _Param) -> task<typename details::_TaskTypeFromParam<_Ty>::_Type>;

But sometimes it can be necessary with templates, when the return type of the function could vary with the arguments.

Say you want a templated function to add variables:

template<typename T>
T add(const T& x, const T& y)
{
    return x + y;
}

That’s great, but you’ll only be able to add variables of the same type. Suppose you would like to be able to add variables of any type (like add((int)1, (double)2)).

template<typename T, typename U>
??? add(const T& x, const U& y)
{
    return x + y;
}

EDIT: note that in C++14 and onwards, it’s legal to write auto add(const T& x, const U& y), without a trailing return type, for function definitions (in other words, when you define the body of your function).


The problem is that you can’t tell in advance what the result type of x + y will be. As templates stand, they could even be non-integral types. (Wouldn’t you like to be able to do add(std::string("x"), "y")?)

Decltype, along with the new function declaration syntax, lets you solve this problem.

template<typename T, typename U>
auto add(const T& x, const U& y) -> decltype(x + y)
{
    return x + y;
}

Decltype “returns” the type of an expression. Since you need x and y to have been declared for decltype(x + y) to work, you need the new syntax.

Leave a Comment