lmi
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [lmi] [PATCH] C++ m11n: range-based for loops


From: Vadim Zeitlin
Subject: Re: [lmi] [PATCH] C++ m11n: range-based for loops
Date: Mon, 16 Jan 2017 18:20:46 +0100

On Mon, 16 Jan 2017 15:43:07 +0000 Greg Chicares <address@hidden> wrote:

GC> +wx_test_paste_census.cpp
GC> We should certainly dispense with the iterator typedef. But compare
GC> your patch to what I committed: do you still want to introduce an
GC> extra variable?

 I think the code using "first" is more clear and not dealing with
iterators is always nice in my book; for the same reason that using
references is better than using pointers: you don't have to wonder if a
reference can be null and if you don't have any iterators, you don't have
to wonder if it can be invalid.

 BTW, I find it useful to have some kind of "once only" helper class, e.g.
(warning: untested pseudo code ahead):

        class do_once_only
        {
        public:
                do_once_only() = default;
                do_once_only(do_once_only const&) = delete;
                do_once_only& operator=(do_once_only const&) = delete;

                explicit operator bool()
                {
                        if (done_)
                                return false;

                        done_ = true;
                        return true;
                }

        private:
                bool done_ = false;
        };

and then use it like this:

        do_once_only skip_comma;
        for(auto const& s : remaining)
            {
            if(!skip_comma)
                message << ",";
            message << " '" << s << "'";
            }


 In another project I have a less general but handy and perhaps more clear
maybe_separator class which is not inserted the first time it's used, with
it the code above would be even simpler:

        maybe_separator maybe_comma(",");
        for(auto const& s : remaining)
            {
            message << maybe_comma << " '" << s << "'";
            }

and still produce the same output.


GC> Compare the change in
GC>   group_quote_pdf_generator_wx::output_document_header()
GC> where we kept the iterator precisely so we could test it against end().

 No, not really. We have to use an iterator there to be able to increment
it inside the loop. An alternative way to do it would involve writing (or
using an existing implementation of) adaptor iterator allowing to iterate
by 2 elements at once and I decided that it wasn't worth doing this.

 Regards,
VZ


reply via email to

[Prev in Thread] Current Thread [Next in Thread]