0

我正在尝试为容器实现一个迭代器和一个反向迭代器,但是,这两个迭代器的返回类型是不同的。

与迭代器相关的代码:

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,就像原来的迭代器一样。谢谢你。

4

0 回答 0