In C++14, you can just use auto as a return type.
1 The auto and decltype(auto) type-specifiers designate a placeholder type that will be replaced later, either by deduction from an initializer or by explicit specification with a trailing-return-type. The auto type-specifier is also used to signify that a lambda is a generic lambda.
C++: “auto” return type deduction The “auto” keyword used to say the compiler: “The return type of this function is declared at the end”. In C++14, the compiler deduces the return type of the methods that have “auto” as return type.
C++ Function Return Types. In C++, function return type is a value returned before a function completes its execution and exits. Let's see some of the most critical points to keep in mind about returning a value from a function.
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.
It's got nothing to do with the simplicity of the function (as a now-deleted duplicate of this question supposed).
Either the return type is fixed (don't use auto
), or dependent in a complex way on a template parameter (use auto
in most cases, paired with decltype
when there are multiple return points).
I want to provide an example where return type auto is perfect:
Imagine you want to create a short alias for a long subsequent function call. With auto you don't need to take care of the original return type (maybe it will change in future) and the user can click the original function to get the real return type:
inline auto CreateEntity() { return GetContext()->GetEntityManager()->CreateEntity(); }
PS: Depends on this question.
Consider a real production environment: many functions and unit tests all interdependent on the return type of foo()
. Now suppose that the return type needs to change for whatever reason.
If the return type is auto
everywhere, and callers to foo()
and related functions use auto
when getting the returned value, the changes that need to be made are minimal. If not, this could mean hours of extremely tedious and error-prone work.
As a real-world example, I was asked to change a module from using raw pointers everywhere to smart pointers. Fixing the unit tests was more painful than the actual code.
While there are other ways this could be handled, the use of auto
return types seems like a good fit.
For scenario 3 I would turn the return type of function signature with the local variable to be returned around. It would make it clearer for client programmers hat the function returns. Like this:
Scenario 3 To prevent redundancy:
std::vector<std::map<std::pair<int, double>, int>> foo() {
decltype(foo()) ret;
return ret;
}
Yes, it has no auto keyword but the principal is the same to prevent redundancy and give programmers who dont have access to the source an easier time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With