This page looks best with JavaScript enabled

What is arrow (->) in function declaration in C++

 ·  ☕ 1 min read · 👀... views

Alternative function syntax

The arrow (->) in function heading in C++ is just another form of function syntax in C++11.
This is standard function declaration:

1
return-type function_name(argument-list) { body-statement }

As C++ grew more complex, it exposed several limits. For example, in C++03 this is not allowed:

1
2
template<class Lhs, class Rhs>
  Ret adding_func(const Lhs &lhs, const Rhs &rhs) {return lhs + rhs;} //Ret must be the type of lhs+rhs

The compiler would not know what Ret is. And this is still not possible with the new introduced decltype keyword:

1
2
template<class Lhs, class Rhs>
  decltype(lhs+rhs) adding_func(const Lhs &lhs, const Rhs &rhs) {return lhs + rhs;} //Not valid C++11

It’s not valid because Lhs and Rhs would not be valid identifiers until after the parser has passed the rest of the function prototype.
To work around this, C++11 introduced a new function declaration syntax, with a trailing-return-type:

1
2
template<class Lhs, class Rhs>
  auto adding_func(const Lhs &lhs, const Rhs &rhs) -> decltype(lhs+rhs) {return lhs + rhs;}

In this syntax, auto and decltype keywords are combined.

References

Share on