[Apologies if this question seems opinionated or discussionworthy.]
I have a class which, although not a collection class per se, does contain an arbitrary number of elements which are primarily constructed via an 'append' method:
append(TypeA thingA, TypeB thingB, TypeC thingC);
Significantly, there is not an auxiliary struct or class anywhere tying together a triple of (thingA
, thingB
, thingC
), nor has one been needed so far -- the class works fine as-is.
Today I decided I needed an iterator for this class, that could return all the things I'd added to it, almost as if it were a collection, after all. The question is, what's the best way to return thingA
, thingB
, and thingC
?
I could belatedly define an auxiliary tuple struct, just so that the iterator could return instances of it. But this seemed a little odd.
What I implemented instead was something along the lines of
class FunnyCollectionIter {
FunnyCollection* _ctx;
unsigned int _i;
public:
FunnyCollectionIter();
const TypeA& thingA() const;
const TypeB& thingB() const;
const TypeC& thingC() const;
FunnyCollectionIter& operator=(const FunnyCollectionIter &rhs);
FunnyCollectionIter& operator++();
bool operator==(const FunnyCollectionIter &rhs) const;
// ...
}
};
And I'm using it with code like this:
FunnyCollectionIter it;
for(it = funnycollection.begin(); it != funnycollection.end(); ++it) {
// now do things with it.thingA(), it.thingB(), and it.thingC()
}
But this seems a little odd, too. Normally (in the STL, at least) you access an iterator either using *
, or ->first
and ->second
. But in the scheme I've implemented, there's no *
, no ->
, no first
and second
(let alone third
?), and the interesting names thingA
, thingB
, and thingC
are methods to invoke, not members to access.
So my question is, is this a poor way to construct an iterator in this situation, and is there a better way?
Aucun commentaire:
Enregistrer un commentaire