开发者

public: typedef other_class::const_iterator my_class::const_iterator - acceptable?

I'm looking for a way to use std::set::const_iterator as const_iterator of my own class.

My code (which actually behaves correct and compiles fine), goes like:

class MyClass{

public:
    typedef std::set<T>::const_iterator con开发者_C百科st_iterator;

const_iterator begin() const {
    return mySet->begin();
}

const_iterator end() const {
    return mySet->end();
}

}; // MyClass

So, my question is: Is my way of using the const_iterator acceptable and also in the STL intended form?

Edit: Related question and answers at How to typedef the iterator of a nested container?


The idea of having the internal type is so that generic code can use your class without prior knowledge of the implementation. The main point is that there is a const_iterator, and that it has the semantics of a constant iterator. The fact that you are borrowing the iterator from the internal type is just an implementation detail that calling code should not care about.

That is, the problem would be not defining the const_iterator internal type, as that would increase coupling in user code, where they would have to use std::set<T>::const_iterator explicitly, and that in turn makes the type of the member part of the interface (i.e. you can no longer change the implementation of the member without breaking user code).


Have a look at other C++ Standard Library container adapters like std::queue. std::queue is just an adapter on top of an underlying container (by default a std::deque).

This is exactly the method used in those adapters. Given that, I would say your implementation is fine.


Yes, of course. You may store a std::set<T>::const_iterator anywhere you like, and making an alias of the type is even more okay.


It's not particularly encapsulated, but a perfectly valid technique.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜