When should I use C++14 automatic return type deduction?

C++11 raises similar questions: when to use return type deduction in lambdas, and when to use auto variables.

The traditional answer to the question in C and C++03 has been "across statement boundaries we make types explicit, within expressions they are usually implicit but we can make them explicit with casts". C++11 and C++1y introduce type deduction tools so that you can leave out the type in new places.

Sorry, but you're not going to solve this up front by making general rules. You need to look at particular code, and decide for yourself whether or not it aids readability to specify types all over the place: is it better for your code to say, "the type of this thing is X", or is it better for your code to say, "the type of this thing is irrelevant to understanding this part of the code: the compiler needs to know and we could probably work it out but we don't need to say it here"?

Since "readability" is not objectively defined[*], and furthermore it varies by reader, you have a responsibility as the author/editor of a piece of code that cannot be wholly satisfied by a style guide. Even to the extent that a style guide does specify norms, different people will prefer different norms and will tend to find anything unfamiliar to be "less readable". So the readability of a particular proposed style rule can often only be judged in the context of the other style rules in place.

All of your scenarios (even the first) will find use for somebody's coding style. Personally I find the second to be the most compelling use case, but even so I anticipate that it will depend on your documentation tools. It's not very helpful to see documented that the return type of a function template is auto, whereas seeing it documented as decltype(t+u) creates a published interface you can (hopefully) rely on.

[*] Occasionally someone tries to make some objective measurements. To the small extent that anyone ever comes up with any statistically significant and generally-applicable results, they are completely ignored by working programmers, in favour of the author's instincts of what is "readable".


Generally speaking, the function return type is of great help to document a function. The user will know what is expected. However, there is one case where I think it could be nice to drop that return type to avoid redundancy. Here is an example:

template<typename F, typename Tuple, int... I>
  auto
  apply_(F&& f, Tuple&& args, int_seq<I...>) ->
  decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(args))...))
  {
    return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(args))...);
  }

template<typename F, typename Tuple,
         typename Indices = make_int_seq<std::tuple_size<Tuple>::value>>
  auto
  apply(F&& f, Tuple&& args) ->
  decltype(apply_(std::forward<F>(f), std::forward<Tuple>(args), Indices()))
  {
    return apply_(std::forward<F>(f), std::forward<Tuple>(args), Indices());
  }

This example is taken from the official committee paper N3493. The purpose of the function apply is to forward the elements of a std::tuple to a function and return the result. The int_seq and make_int_seq are only part of the implementation, and will probably only confuse any user trying to understand what it does.

As you can see, the return type is nothing more than a decltype of the returned expression. Moreover, apply_ not being meant to be seen by the users, I am not sure of the usefulness of documenting its return type when it's more or less the same as apply's one. I think that, in this particular case, dropping the return type makes the function more readable. Note that this very return type has actually been dropped and replaced by decltype(auto) in the proposal to add apply to the standard, N3915 (also note that my original answer predates this paper):

template <typename F, typename Tuple, size_t... I>
decltype(auto) apply_impl(F&& f, Tuple&& t, index_sequence<I...>) {
    return forward<F>(f)(get<I>(forward<Tuple>(t))...);
}

template <typename F, typename Tuple>
decltype(auto) apply(F&& f, Tuple&& t) {
    using Indices = make_index_sequence<tuple_size<decay_t<Tuple>>::value>;
    return apply_impl(forward<F>(f), forward<Tuple>(t), Indices{});
}

However, most of the time, it is better to keep that return type. In the particular case that I described above, the return type is rather unreadable and a potential user won't gain anything from knowing it. A good documentation with examples will be far more useful.


Another thing that hasn't been mentioned yet: while declype(t+u) allows to use expression SFINAE, decltype(auto) does not (even though there is a proposal to change this behaviour). Take for example a foobar function that will call a type's foo member function if it exists or call the type's bar member function if it exists, and assume that a class always has exacty foo or bar but neither both at once:

struct X
{
    void foo() const { std::cout << "foo\n"; }
};

struct Y
{
    void bar() const { std::cout << "bar\n"; }
};

template<typename C> 
auto foobar(const C& c) -> decltype(c.foo())
{
    return c.foo();
}

template<typename C> 
auto foobar(const C& c) -> decltype(c.bar())
{
    return c.bar();
}

Calling foobar on an instance of X will display foo while calling foobar on an instance of Y will display bar. If you use the automatic return type deduction instead (with or without decltype(auto)), you won't get expression SFINAE and calling foobar on an instance of either X or Y will trigger a compile-time error.


It's never necessary. As to when you should- you're going to get a lot of different answers about that. I'd say not at all until its actually an accepted part of the standard and well supported by the majority of major compilers in the same way.

Beyond that, its going to be a religious argument. I'd personally say never- putting in the actual return type makes code clearer, is far easier for maintenance (I can look at a function's signature and know what it returns vs actually having to read the code), and it removes the possibility that you think it should return one type and the compiler thinks another causing problems (as has happened with every scripting language I've ever used). I think auto was a giant mistake and it will cause orders of magnitude more pain than help. Others will say you should use it all the time, as it fits their philosophy of programming. At any rate, this is way out of scope for this site.