[openbeos] Coding Suggestion -- Templates, Iterators

  • From: "Daniel Reinhold" <danielr@xxxxxxxxxxxxx>
  • To: "OpenBeOS mailing list" <openbeos@xxxxxxxxxxxxx>
  • Date: Sat, 27 Oct 2001 13:47:40 CDT

At the risk (ah heck, certainty) of starting a language war, I have a 
couple of suggestion regarding coding style with C++.

I came across the following code today (actually its from CppTest):

void TestSuite::run (TestResult *result)
{
    for (std::vector<Test *>::iterator it = m_tests.begin ();
            it != m_tests.end ();
            ++it) {
                // loop code
    }

}

(I've snipped out the loop code)

A couple of things occur to me as I stare at this code (besides the 
fact that I'm not crazy about C++). One is that the template 
declaration syntax is often extremely awkward to read. In many cases, 
it makes sense to typedef these buggers into something more friendly. 
In this example, I would do:

typedef std::vector<Test *>::iterator TestIterator;

Another thing is that iterators are pretty common, so I think having a 
standard macro for traversing with one would be very useful. Here's my 
suggestion:

#define foreach(elem,set) for (elem = set.begin (); elem != set.end (); 
++elem)

Oh, I know, I can hear the groaning out there... "we don't use #define 
macros -- that's old-style, icky C crap that we sophisticated C++ 
programmers don't use". Maybe, but I still think macros are extremely 
useful when used sparingly and judiciously. They're awfully good at 
hiding uglies.

Now using those two code snippets above, I can rewrite the example 
(using OpenTracker formatting) as follows:

void
TestSuite::run (TestResult *result)
{
        TestIterator i;
        foreach (i, m_tests) {
                // loop code
        }
}

Now that's a bit cleaner/clearer. When reading the iterator loop, you 
have to mentally put the word "in" in there. IOW, read it as "for each 
i in m_tests".

So whadya think? Love it? Hate it?

Other related posts: