Function return type deduction in C++14

C++11 introduced the auto keyword as a placeholder for types. It could be used for declaring variables but also for the return type of a function, given than you use a new syntax with a trailing type at the end of the function.

or

This is a bit cumbersome and too explicit so C++14 takes the next step and makes the trailing return type unnecessary. Under C++14 the above examples can be simply written as:

and

There are several things to keep in mind:

  • if a function has more than one return statement they all must deduce the same type
  • a recursive function can have an auto return type only if it has a non-recursive return statement before the recursive call.
  • a function with an auto return type can be forward declared, but cannot be used until it has been defined

In my personal opinion auto return type should be used with caution. It can make the code harder to read and maintain (you don’t know the type just by looking at the signature), harder to document (automatic documenting tools use the signature to produce documentation), and can lead to situations when the developer expects one return type but the compiler generates another.

Additional readings:

One thought on “Function return type deduction in C++14

  1. Mathias Gaunard

    Bear in mind that

    template
    auto foo(T value) -> decltype(value.bar())
    {
    return value.bar();
    }

    and

    template
    auto foo(T value)
    {
    return value.bar();
    }

    are not equivalent.

    The symbols are not the same and they won’t behave the same if value.bar() is not a valid expression for the T given.

    Reply

Leave a Reply