我正在尝试为容器实现迭代器和反向迭代器,但是,这两个迭代器的返回类型不同。
与迭代器有关的相关代码:
template <typename T, size_t N>
ActivePtr<T> ObjectPool<T, N>::ObjectPoolIterator::operator*()
{
return curr->data[index].MakePtr();
}
template <typename T, size_t N>
typename ObjectPool<T, N>::ObjectPoolIterator ObjectPool<T, N>::begin() const
{
return ObjectPoolIterator(head, nullptr, 0);
}
template <typename T, size_t N>
typename ObjectPool<T, N>::ObjectPoolIterator ObjectPool<T, N>::end() const
{
return ObjectPoolIterator(nullptr, tail, 0);
}
template <typename T, size_t N>
std::reverse_iterator<typename ObjectPool<T, N>::ObjectPoolIterator> ObjectPool<T, N>::rbegin() const
{
return std::make_reverse_iterator(end());
}
template <typename T, size_t N>
std::reverse_iterator<typename ObjectPool<T, N>::ObjectPoolIterator> ObjectPool<T, N>::rend() const
{
return std::make_reverse_iterator(begin());
}
与用例有关的代码:
for (ObjectPool<long long, 100000>::ObjectPoolIterator i = objectPool.begin(); i != objectPool.end(); ++i)
{
objectPool.Erase(*i); // works fine
}
for (std::reverse_iterator<ObjectPool<long long, 100000>::ObjectPoolIterator> i = objectPool.rbegin(); i != objectPool.rend(); ++i)
{
objectPool.Erase(*i); // error: unable to convert from long long to ActivePtr<long long>
}
旁注:ActivePtr上的一元*确实会返回T&。也许这可能影响了std :: reverse_iterator确定返回类型的判断?
除了定义自己的反向迭代器之外,还有其他解决方法吗? 我希望反向迭代器仍然像原始迭代器一样向我返回ActivePtr。 谢谢。