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

前端 未结 7 2113
南笙
南笙 2020-11-28 19:05

With GCC 4.8.0 released, we have a compiler that supports automatic return type deduction, part of C++14. With -std=c++1y, I can do this:

auto          


        
相关标签:
7条回答
  • 2020-11-28 19:25

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

    0 讨论(0)
  • 2020-11-28 19:26

    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.

    0 讨论(0)
  • 2020-11-28 19:31

    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.

    0 讨论(0)
  • 2020-11-28 19:33

    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".

    0 讨论(0)
  • 2020-11-28 19:33

    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.

    0 讨论(0)
  • 2020-11-28 19:36

    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.

    0 讨论(0)
提交回复
热议问题