無需升壓解決方案。但是,如果您有權訪問boost庫 - 請按照提議使用Filter Iterator。
template <typename TCollection, typename T>
class Iterator
{
public:
typedef typename TCollection::iterator iterator;
typedef typename TCollection::value_type value_type;
Iterator(const TCollection& collection,
iterator it):
collection_(collection),
it_(it)
{
moveToNextAppropriatePosition(it_);
}
bool operator != (const Iterator& rhs)
{
return rhs.it_ != it_;
}
Iterator& operator++()
{
++it_;
moveToNextAppropriatePosition(it_);
return *this;
}
Iterator& operator++(int);
Iterator& operator--();
Iterator& operator--(int);
value_type& operator*()
{
return *it_;
}
value_type* operator->()
{
return &it_;
}
private:
const TCollection& collection_;
iterator it_;
void moveToNextAppropriatePosition(iterator& it)
{
while (dynamic_cast<T*>(*it) == NULL && it != collection_.end())
++it;
}
};
class A
{
public:
A(){}
virtual ~A(){}
virtual void action()
{
std::cout << "A";
}
};
class B: public A
{
public:
virtual void action()
{
std::cout << "B";
}
};
int main()
{
typedef std::vector< A* > Collection;
Collection c;
c.push_back(new A);
c.push_back(new B);
c.push_back(new A);
typedef Iterator<Collection, B> CollectionIterator;
CollectionIterator begin(c, c.begin());
CollectionIterator end(c, c.end());
std::for_each(begin, end, std::mem_fun(&A::action));
}
是不是可以讓你自己的迭代器(或子類),將跳過除SubType對象以外的任何東西? – 2009-04-21 19:49:50