(*it)-> cleanup.

I ran into this today which seemed excessively verbose. Does anyone have a cleaner way of doing it?

1
2
3
4
5
6
7
8
9
10
11
class pet
{
public:
    virtual void eat();
};

class dog : public pet
{
public:
    void eat();
};


Then:
1
2
3
typedef std::vector<pet*>::iterator petIter;
std::vector<pet*> pets;
pets.push_back(new dog());


And here's the verbose part:
1
2
for (petIter it = pets.begin(); it != pets.end(); ++it)
    (*it)->eat();


(*it)->function(); just seems so not elegant, but this type of aggregation/inheritance is so common in C++ and is what C++ was really designed for. There has to be a better way.
Range-based for loop? And smart pointers?
Stuck in VS2008 for work. No C++11 there. I do like the range-based for loops, but I'll look-up smart pointers. Maybe it would be worth re-implementing in our utility library.
The only C++03 solutions I can think of make it more complex/annoying for the surrounding code. AFAIK I haven't seen anything better than what you have, and it's not too terribly annoying. Sometimes I have fun:
1
2
for (petIter it = pets.begin(); it != pets.end(); ++it)
    it->operator->()->eat();
That's hilarious.

I had tried it->-> just for fun, but of course it didn't compile.
You can go cleaner it you throw away standardization...

1
2
	for each (pet* p in pets)
		p->eat();


Andy
Last edited on
Stuck in VS2008 for work. No C++11 there.


1
2
3
4
5
6
7
8
#include <functional>
#include <algorithm>

// ...

    std::for_each(pets.begin(), pets.end(), std::tr1::mem_fn(&pet::eat));

// ... 
Wow cool. I had not thought of that at all.
I often forget about the technical releases (which work quite well in VC++2008). Nice one cire!
Topic archived. No new replies allowed.