[C++-sig] Can't call injected method taking SmartPtr<Derived> with derived object...

Alex Mohr amohr at pixar.com
Mon Dec 19 20:56:11 CET 2005


I'm having a bit of trouble with inheritance and injected methods. 
Here's a small example.  In this example, SmartPtr is a custom smart 
pointer much like boost::shared_ptr.

--------------------------------------------------------
class Base { public: virtual ~Base() {} };

class Derived : public Base {
   public:
     virtual ~Derived() {}
     static SmartPtr<Base> GetAsBase(SmartPtr<Derived> const &p) {
         return SmartPtr<Base>(p);
     }
     string derivedMethod() { return "Derived Method"; }
};
static SmartPtr<Derived> newDerived() { ...makes a new derived... }

static string injectedMethod(SmartPtr<Derived> const &self) {
     return "Injected Method";
}

BOOST_PYTHON_MODULE(foo) {
     class_<Base, SmartPtr<Base> >("Base", no_init);
     class_<Derived, SmartPtr<Derived>, bases<Base> >
         ("Derived", no_init)
         .def("__init__", make_constructor(newDerived))
         .def("derivedMethod", &Derived::derivedMethod)
         .def("injectedMethod", injectedMethod<Derived>)
         .def("GetAsBase", &Derived::GetAsBase).staticmethod("GetAsBase")
     ;
}

 >>> d = Derived()
 >>> d.derivedMethod()
'Derived Method'
 >>> d.injectedMethod()
'Injected Method'
 >>> b = Derived.GetAsBase(d)
 >>> type(b)
<class 'foo.Derived'>
 >>> b.derivedMethod()
'Derived Method'
 >>> b.injectedMethod()
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
Boost.Python.ArgumentError: Python argument types in
     Derived.injectedMethod(Derived)
did not match C++ signature:
     injectedMethod(SmartPtr<Derived>)
--------------------------------------------------------

Here are some observations.  1) This actually works right if I make the 
C++ injectedMethod take 'Derived const &' rather than 'SmartPtr<Derived> 
const &'.  2) The whole example works fine *as-is* if I use 
boost::shared_ptr rather than my own custom smart pointer.

Any help is greatly appreciated.

Thanks,

Alex



More information about the Cplusplus-sig mailing list