我需要存储 Base 类型的对象,以及派生类型 BaseDerivedA 和 BaseDerivedB 的对象。这些对象需要在内存中对齐。我想提供一个迭代所有对象的迭代器。我想避免存储 Base 指针向量的内存开销。
为此,我构建了以下容器
struct Container {
std::vector<Base> bases;
std::vector<BaseDerivedA> derivedAs;
std::vector<BaseDerivedB> derivedBs;
// Iterator over the three vectors
all_iterator<Base> all_begin(){ return all_iterator(bases[0],this); }
all_iterator<Base> end_begin(){ return all_iterator(nullptr,this); }
// Where all_iterator is defined as
template < class T >
struct all_iterator
: public boost::iterator_facade< all_iterator<T>,
T, boost::forward_traversal_tag>
{
all_iterator() : it_(0) {}
explicit all_iterator(T* p, Container* c) // THIS JUST FEELS WRONG
: it_(p), c_(c) { }
private:
friend class boost::iterator_core_access;
T* it_;
Container* c_;
void increment() {
if (it_ == static_cast<T*>(&(c_->bases[c_->bases.size()-1]))) {
it_ = static_cast<T*>(&(c_->derivedAs[0]));
} else if (it_ == static_cast<T*>(&(c_->derivedAs[ds_->derivedAs.size()-1]))) {
it_ = static_cast<T*>(&(c_->derivedBs[0]));
} else if (it_ == static_cast<T*>(&(c_->derivedBs[ds_->derivedBs.size()-1]))) {
it_ = nullptr; // THIS DOES ALSO FEEL WRONG
} else {
++it_;
}
}
bool equal(all_iterator const& other) const {
return this->it_ == static_cast<T*>(other.it_);
}
T& dereference() const { return *it_; }
};
我使用 nullptr 作为过去的迭代器以及很多演员。我还向我的迭代器传递了一个指向数据结构的指针。
是否有更好的方法来迭代三个包含 Base 类型或从 base 派生的类型的向量?