[C++-sig] Re: smart pointer and polymorphism problem
Raoul Gough
RaoulGough at yahoo.co.uk
Thu Nov 27 11:15:39 CET 2003
Christophe Pradal <christophe.pradal at cirad.fr> writes:
> I use an intrusive refcount pointer as described by Scott Meyers in
> "More effective C++" and improved by adding template casting operator
> (Scott Meyers again, but later).
> Considering RefCountObject as the base class for pointed objects and
> RefCountPtr the smart pointer template, I built a small example
> reproducing the error:
>
> class O: public virtual RefCountObject
> {
> public:
> O(): RefCountObject() {}
> virtual ~O() {}
> virtual int get() = 0;
> };
>
> class A: public O
> {
> public:
> int _a;
> A(): O(), _a(1) {}
> virtual ~A( ) {}
> int get() {return _a;}
> };
>
> typedef RCPtr<O> OPtr;
> typedef RCPtr<A> APtr;
>
> int foo(const OPtr& p) { return p->get(); }
>
> BOOST_PYTHON_MODULE(test)
> {
> class_< O, OPtr, boost::noncopyable >("O", no_init);
> class_< A, APtr, bases<O>,boost::noncopyable >("A", init<>());
> def( "foo",foo );
> };
>
> In python, the following test fail:
>
> >>> import test
> >>> a= test.A()
> >>> test.foo(a)
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> Boost.Python.ArgumentError: Python argument types in
> test.foo(A)
> did not match C++ signature:
> foo(class TOOLS::RefCountPtr<class O>)
>
>
> Any idea?
When there is an implicit conversion between types (other than derived
to base conversions, I mean), you can register it with something like:
boost::python::implicitly_convertible<A, O>();
Of course, in this case you already have this conversion since you
registered O as a base class of A. I notice that foo takes a smart
pointer rather than a reference to O, so maybe you would need this:
boost::python::implicitly_convertible<RefCountPtr<A>, RefCountPtr<O> >();
On the other hand, I'm not sure if that will work because Ptr<A> and
Ptr<O> are only held types and not the actual class_<> types. It's
worth a go I suppose, but you wouldn't have any problem if foo took an
O &.
--
Raoul Gough.
export LESS='-X'
More information about the Cplusplus-sig
mailing list