Re: example vector wrapper
On 19 Mar, 05:44, "kwikius" <a...@servocomm.freeserve.co.uk> wrote:
On 19 Mar, 03:31, "Tim H" <thoc...@gmail.com> wrote:
I'm working on a class that wraps a vector. In fact, it behaves very
much like a vector. I've read it's "bad" to subclass vector, since it
is not intended for that use.
std containers don't have virtual destructor.
struct A : public vector<int>
{
~A(){ do something very important }
};
vector<int> * p = new A;
....
delete p;
this will not call A's destructor.
If you don't use it this way it is perfectly
fine to subclass any of the std containers.
So I am wrapping it. I have a lot of
simple pass-thru methods, which is fine.
Where it all breaks down is iterators. The underlying vector is
storing annotated data that the caller does not need to see. Think of
it this way:
Also of interest might be The boost iterator adaptors. I have never
really figured what these are about, but they may provide some
insights:
http://www.boost.org/libs/iterator/doc/index.html
It seems to me that you don't want to wrap a vector
but just its iterator. boost::iterators is perfect for that.
simple example:
void fun(int);
struct A
{
int n;
};
vector<A> v;
now I want to iterate through v and execute fun
for each A. since fun takes int I need to adapt
vector's iterator
struct my_iterator : public boost::iterator_facade
< my_iterator
// deference type
, int
// we only want to go one way
, boost::forward_traversal_tag >
{
vector<A>::iterator it_;
my_iterator(vector<A>::iterator it)
: it_(it)
{}
// you need to implement these methods
// to satisfy iterator_facade's requirements.
my_iterator(){}
void increment() { ++it_; }
bool equal(my_iterator const& other) const
{
return it_ == other.it_;
}
reference_type dereference() const
{
return (*it_).n;
}
};
now you can write:
std::for_each(my_iterator(v.begin()), my_iterator(v.end())
, bind(&fun, _1));