|
Boost Users : |
From: Hickman, Greg (greg.hickman_at_[hidden])
Date: 2002-11-01 17:21:37
The following code illustrates a problem I'm having trying to use
iterator_adaptor. Basically, I have a container of shared pointers to
mutable, and I'd like to provide a const_iterator to clients that disallows
modification of both the shared pointer as well as the pointee.
Specifically, I'd like to prevent clients from writing the two lines
preceeding the return from main below. Can anyone help?
Thanks,
Greg
#include <boost/iterator_adaptors.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
using namespace boost;
using namespace std;
struct Shape {
virtual ~Shape() {}
virtual void draw() const = 0;
virtual void update() = 0;
};
struct Concrete_shape : Shape {
void draw() const {}
void update() {}
};
typedef shared_ptr<Shape> Shape_ptr;
typedef shared_ptr<const Shape> Const_shape_ptr;
struct Picture {
typedef vector<Shape_ptr> Shapes;
// Declare a const_iterator that converts
// to the underlying Shape_ptr to a
// Const_shape_ptr. Since the returned
// Const_shape_ptr is a temporary, clients
// shouldn't be allowed to modify it.
typedef iterator_adaptor<
Shapes::const_iterator,
default_iterator_policies,
value_type_is<Const_shape_ptr>,
reference_is<const Const_shape_ptr>,
iterator_category_is<input_iterator_tag>
> const_iterator;
const_iterator begin() const {
return const_iterator(shapes_.begin());
}
Shapes shapes_;
};
int main(int argc, char* argv[])
{
Picture pic;
const Picture& cpic = pic;
pic.shapes_.push_back(Shape_ptr(new Concrete_shape));
Picture::const_iterator i = cpic.begin();
// I'd like to prevent clients from writing...
i->reset(new Concrete_shape);
*i = Const_shape_ptr(new Concrete_shape);
return 0;
}
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net