views:

246

answers:

3

I have a container of smart pointers to mutable objects. I have to write two *for_each* loops, one for accessing the objects as read-only data and another for mutable data. The compiler is telling me that std::vector< boost::shared_ptr<Object> > is not the same as std::vector< boost::shared_ptr<const Object> >, note the const.

Here is my example code:

#include <vector>
#include "boost/shared_ptr.hpp"
#include <iterator>

class Field_Interface
{ ; };
typedef boost::shared_ptr<Field_Interface> Ptr_Field_Interface;
typedef boost::shared_ptr<const Field_Interface> Ptr_Const_Field_Interface;

struct Field_Iterator
  : std::input_iterator<std::forward_iterator_tag, Ptr_Field_Interface>
{
  // forward iterator methods & operators...
};

struct Const_Field_Iterator
  : std::input_iterator<std::forward_iterator_tag, Ptr_Const_Field_Interface>
{
  // forward iterator methods & operators...
};

struct Field_Functor
{
  virtual void operator()(const Ptr_Field_Interface&) = 0;
  virtual void operator()(const Ptr_Const_Field_Interface&) = 0;
};

class Record;
typedef boost::shared_ptr<Record> Ptr_Record;
typedef boost::shared_ptr<const Record> Ptr_Const_Record;

class Record_Base
{
  protected:
    virtual Field_Iterator beginning_field(void) = 0;
    virtual Field_Iterator ending_field(void) = 0;
    virtual Const_Field_Iterator const_beginning_field(void) = 0;
    virtual Const_Field_Iterator const_ending_field(void) = 0;

    void for_each(Field_Functor * p_functor)
    {
       Field_Iterator iter_begin(beginning_field());
       Field_Iterator iter_end(ending_field());
       for (; iter_begin != iter_end; ++ iter_begin)
       {
         (*p_functor)(*iter_begin);
       }
     }
};

class Record_Derived
{
public:
   typedef std::vector<Ptr_Field_Interface> Field_Container;
   typedef std::vector<Ptr_Record>          Record_Container;
private:
   Field_Container m_fields;
   Record_Container m_subrecords;
};

Given all the above details, how do I implement the pure abstract methods of Record_Base in Record_Derived?

I've tried:

  • returning m_fields.begin(), which
    returns conversion errors (can't convert std::vector<...> to Field_Iterator)
  • returning &m_fields[0], which is dangerous, because it assumes stuff about the internals of std::vector.

BTW, I'm not using std::for_each because I have to iterate over a container of fields and a container of sub-records.

A: 

I would suggest not to write an own iterator when you use a common container type. Writing an own iterator makes sense when you write an own container. However, when you are planning to write a custom iterator have a look at the Boost.Iterator package.

Rupert Jones
A: 

If you want to hide std::vector and its iterators from the user, then you will need to provide polymorphic iterators to go along with your polymorphic RecordBase container. Check out any_iterator from the Adobe ASL library. These links may also be helpful.

However, instead of going to all that trouble, you should consider using the Composite and Visitor patterns in your design. See my other answer.

Emile Cormier
+1  A: 

What you're doing resembles both the Composite and Visitor patterns. Those two patterns mesh well together, so it seems you are on the right track.

To implement the composite pattern, assign the following roles (refer to Composite pattern UML diagram):

  • Leaf -> Field
  • Composite -> Record
  • Component -> Abstract base class of Field and Record (can't think of a good name)

Component operations that are called on Composite types, are passed on recursively to all children (Leaves and other nested Composite types).

To implement the Visitor pattern, overload operator() in your functor classes for each Component subtype (Field and Record).

I recommend that you get a copy of the Design Patterns book by the "Gang of Four", which explains these concepts better and goes into much more detail than I possibly can.

Here is some sample code to whet your appetite:

#include <iostream>
#include <vector>
#include "boost/shared_ptr.hpp"
#include "boost/foreach.hpp"

class Field;
class Record;

struct Visitor
{
    virtual void operator()(Field& field) = 0;
    virtual void operator()(Record& field) = 0;
};

class Component
{
public:
    virtual bool isLeaf() const {return true;}
    virtual void accept(Visitor& visitor) = 0;
};
typedef boost::shared_ptr<Component> ComponentPtr;

class Field : public Component
{
public:
    explicit Field(int value) : value_(value) {}
    void accept(Visitor& visitor) {visitor(*this);}
    int value() const {return value_;}

private:
    int value_;
};

class Record : public Component
{
public:
    typedef std::vector<ComponentPtr> Children;
    Record(int id) : id_(id) {}
    int id() const {return id_;}
    Children& children() {return children_;}
    const Children& children() const {return children_;}
    bool isLeaf() const {return false;}
    void accept(Visitor& visitor)
    {
        visitor(*this);
        BOOST_FOREACH(ComponentPtr& child, children_)
        {
            child->accept(visitor);
        }
    }

private:
    int id_;
    Children children_;
};
typedef boost::shared_ptr<Record> RecordPtr;

struct OStreamVisitor : public Visitor
{
    OStreamVisitor(std::ostream& out) : out_(out) {}
    void operator()(Field& field) {out_ << "field(" << field.value() << ") ";}
    void operator()(Record& rec) {out_ << "rec(" << rec.id() << ") ";}
    std::ostream& out_;
};

int main()
{
    RecordPtr rec(new Record(2));
        rec->children().push_back(ComponentPtr(new Field(201)));
        rec->children().push_back(ComponentPtr(new Field(202)));
    RecordPtr root(new Record(1));
        root->children().push_back(ComponentPtr(new Field(101)));
        root->children().push_back(rec);

    OStreamVisitor visitor(std::cout);
    root->accept(visitor);
}

In Record, you may want to provide methods for manipulating/accessing children, instead of returning a reference to the underlying children vector.

Emile Cormier
@Emile: Thanks, I'm familiar with Visitor, I'll refresh my memory with the Composite pattern. An idea struck me: Simplify `Record_Base` to *container*, and convert to standard container idioms so that `std::for_each` will work on the `Record_Base` container.
Thomas Matthews