Search code examples
c++c++11trailing-return-type

Trailing return type in non-template functions


I have seen people using the following syntax to implement functions:

auto get_next() -> int 
{
   /// ...
}

Instead of:

int get_next()
{
   /// ...
}

I understand both and I know that the trailing return type syntax is useful for template code using decltype. Personally I would avoid that syntax for other code since when reading code I prefer to read the concrete return type of a function first, not last.

Is there any advantage in using the trailing return type syntax for non-template code as shown above (except personal preference or style)?


Solution

  • In addition to sergeyrar's answer, those are the points I could imagine someone might like about trailing return types for non-template functions:

    1. Specifying a return type for lambda expressions and functions is identical w.r.t. the syntax.

    2. When you read a function signature left-to-right, the function parameters come first. This might make more sense, as any function will need the parameters to produce any outcome in the form of a return value.

    3. You can use function parameter types when specifying the return type (the inverse doesn't work):

      auto f(int x) -> decltype(x)
      {
          return x + 42;
      }
      

      That doesn't make sense in the example above, but think about long iterator type names.