为容器生成成员类型
当我定义自己的容器时,我必须提供十几个成员类型,例如:
typedef T& reference;
typedef const T& const_reference;
typedef T* iterator;
typedef const T* const_iterator;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
是否有一个我可以继承的基类模板,类似于我自己的 std::iterator
迭代器?
When I define my own containers, I have to provide a dozen of member types, for example:
typedef T& reference;
typedef const T& const_reference;
typedef T* iterator;
typedef const T* const_iterator;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
Is there a base class template I can inherit from, similar to std::iterator<T>
for my own iterators?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您需要经常这样做,那么我想您可以创建一个
并继承它。在标准库中,std::allocator 确实定义了所有这些 typedef,因此从它继承在技术上可以完成您想要的操作,并且不应强加任何运行时开销。不过,我仍然认为最好编写自己的 typedef。
If you need to do this often, then I guess you could create a
And inherit from this. In the standard library,
std::allocator
does define all those typedefs, thus inheriting from it would technically do what you wanted and should not impose any runtime overhead. I still think it's better to just write your own typedefs, though.boost::iterator 可以满足这种特定需求。
我希望本教程能让事情变得清晰 http ://www.boost.org/doc/libs/1_46_0/libs/iterator/doc/iterator_facade.html#tutorial-example
There is boost::iterator for this specific need.
I hope this tutorial will make things clear http://www.boost.org/doc/libs/1_46_0/libs/iterator/doc/iterator_facade.html#tutorial-example
不,但这是个好主意。 OTOH,这将使从容器内引用这些类型变得更加困难,因为它们将是基类中依赖于派生类的模板参数的标识符。这可能会成为一件麻烦事。
No, but it's a nice idea. OTOH, it would make it harder to refer to these types from within the container, because they'd be identifiers in a base class dependent on the derived class' template parameters. That can become a nuisance.