My requirements are the same as those asked in the question "Using Iterators to hide internal container and achieve generic operation over a base container"[1] on Stack Overflow. I have a generic pure virtual base container class, which needs to provide an iterator that is STL-compliant so that I can use it with
我的实现是有效的,我想知道这种实现有没有任何缺点,请帮助我决定使用适当的实现来设计。我在github上添加了完整的工作示例代码:https://gist.github.com/3847688 参考:
#include <algorithm>
in C++ algorithms. My implementation uses only a single class instead of two classes, as in the [1] solution.
Base pure virtual class:
class BaseItr
{
public:
class iterator : public std::iterator<std::input_iterator_tag, int>
{
public:
iterator() : _in(NULL) {}
inline iterator(const iterator& org) : _in(org._in) {}
inline iterator& operator=(const iterator& other) { _in = other._in; return *this; }
virtual inline int operator * () { return _in->operator*(); }
virtual inline iterator& operator++() { (*_in)++; return *this; }
virtual inline iterator& operator++(int unused) { (*_in)++; return *this; }
virtual inline bool operator==(const iterator& other)
{
return *(*_in) == *(*(other._in));
}
virtual inline bool operator!=(const iterator& other)
{
return *(*_in) != *(*(other._in));
}
// would use shared pointer insted of this
//~iterator() { if(_in) { delete _in; } }
static inline iterator New(iterator *in) { return iterator(in); }
private:
iterator(iterator *in) : _in(in) {}
iterator *_in;
};
virtual iterator begin() = 0;
virtual iterator end() = 0;
};
实现
class Itr : public BaseItr
{
private:
class iterator : public BaseItr::iterator
{
public:
iterator(int val) : _val(val), BaseItr::iterator() {}
int operator * () { return _val; }
inline iterator& operator++() { ++_val; return *this; }
inline iterator& operator++(int unused) { _val++; return *this; }
private:
int _val;
};
BaseItr::iterator _begin;
BaseItr::iterator _end;
public:
inline Itr(int start, int end)
{
_begin = BaseItr::iterator::New(new iterator(start));
_end = BaseItr::iterator::New(new iterator(end));
}
BaseItr::iterator begin() { return _begin; }
BaseItr::iterator end() { return _end; }
};
我的实现是有效的,我想知道这种实现有没有任何缺点,请帮助我决定使用适当的实现来设计。我在github上添加了完整的工作示例代码:https://gist.github.com/3847688 参考:
std::unique_ptr
代替虚拟的clone
吗? - Kamstd::unique_ptr
处理所有权,clone
处理复制。你可以同时使用两者。 - Matthieu M.