Trailing return type in non-template functions

735 views Asked by At

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)?

3

There are 3 answers

0
lubgr On BEST ANSWER

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.

0
Andreas Brunnet On

Well you already mentioned the major use case of the trailing return type. It's usage if the return type depends on the arguments. If we exclude that use case the only advantage you might gain is an enhanced readability of your code, especially if your return type is a bit more complex, but you don't have a technical benefit of using the trailing return in that scenario.

1
manish ma On

One potential benefit is that it makes all of your declared function names line up:

auto get_next(int x, int y) -> int;
auto divide(double x, double y) -> double;
auto printSomething() -> void;
auto generateSubstring(const std::string &s, int start, int len) -> std::string;

source: https://www.learncpp.com/cpp-tutorial/the-auto-keyword/