how do i declare a reference to a boost shared pointer

E

eric

Can I declare a pure virtual member function which accepts as input a
boost shared pointer to an object of a base class, such that
- concrete implementations of the function can redirect the pointer to
a new object
- clients of the function can pass in as input a boost shared pointer
to an object of a derived class
?

Consider the following classes in the problem domain:

class Serializable {};
class Foo : public Serializable {};
class Bar : public Foo {};

Here is the pure virtual member function I would like to declare:

class Serializer {
public:
virtual void serializeObject(boost::shared_ptr < Serializable >
&) = 0;
}

And the relevant subset of one of its concrete implementations:

class XmlReader : public Serializer {
virtual void serializeObject(boost::shared_ptr < Serializable >
&p) {
p = boost::shared_ptr < Serializable > (new Bar());
}
}

The client would call the function like this:

boost::shared_ptr < Foo > foo;
XmlSerializer s;
s.serializeObject(foo);

The above code doesn't compile, the error message from VC6 is

test.cpp(72) : error C2664: 'serializeObject' : cannot convert
parameter 1 from 'class boost::shared_ptr<class Foo>' to 'class
boost::shared_ptr<class Serializable> &'
A reference that is not to 'const' cannot be bound to a
non-lvalue

The closest I can get is to declare the function like this:

class XmlReader : public Serializer {
virtual boost::shared_ptr < Serializable > p serializeObject()
{
boost::shared_ptr < Serializable > ret;
ret = boost::shared_ptr < Serializable > (new Bar());
return ret;
}
}

And call it like this:

foo = boost::dynamic_pointer_cast< Foo >(s.serializeObject());

But that's not ideal for my purposes, I would prefer to have a function
which modifies its inputs and returns void.

I can't implement the function as a template because I need it to be
virtual.

Any assistance gratefully received.

Regards,
Eric
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top