[Development] RFC: more liberal 'auto' rules?

Marc Mutz marc.mutz at kdab.com
Sat Dec 5 20:01:00 CET 2015


On Saturday 05 December 2015 13:46:53 Julien Blanc wrote:
> Le samedi 05 décembre 2015 à 12:08 +0000, Bubke Marco a écrit :
[...]
> whereas i prefer
>     template<typename List> void algorithm(List& input)
>     {
>         typedef typename List::value_type Serializable;
>         // there are some requirements on List : item_type must be
>         // Serializable : now i can look the doc to see what a
>         // Serializable is
>         Serializable& first = input.front();
>         // i know what to expect from first, which methods i can call
>         ...
>     }
[...]

Thank YOU! That's the PERFECT example of why you should use _auto_! In the 
best of Qt traditions:

   You're Doing It Wrong!

If you don't see why, try to pass a C array to your function... There's a 
_reason_ we have std::begin(), and a _reason_ why we have iterator_traits.

The _correct_ way to write this is without auto or decltype is:

    template <typename List>
    void algorithm(List &list) {
        using namespace std;
        // no decltype, so way to refer to decltype(begin(list),
        // so need to defer to a helper:
        algorithm_impl(begin(list), end(list));
    }
    template <typename ForwardIterator>
    void algorithm_impl(ForwardIterator first, ForwardIterator last) {
        if (first == last)
            return;
        typedef typename std::iterator_traits<ForwardIterator>::value_type
            Serializable;
        // useless comments
        Serializable &start = *first:
    }

Well, or, with auto:

   template <typename List>
   void algorithm(List &list) {
       using namespace std;
       auto first = begin(list), last = end(list);
       if (first == last)
           return;
       auto &start = *first;
       ....
   }

Everyone who claims that the first one is more readable is crazy.

And please don't _anyone_ out yourself as _actually_ believing that the first 
is more readable, because then I would have personally insulted you, and I 
don't want to do that. Let's hope common sense prevails and we all get out of 
this awkward situation with saved faces...

Thanks,
Marc

-- 
Marc Mutz <marc.mutz at kdab.com> | Senior Software Engineer
KDAB (Deutschland) GmbH & Co.KG, a KDAB Group Company
Tel: +49-30-521325470
KDAB - The Qt Experts



More information about the Development mailing list