使用std :: shared_ptr的Boost.Python和Polymorphic Behavior

时间:2012-04-17 10:25:25

标签: c++ c++11 polymorphism shared-ptr boost-python

我想知道在使用A而不是B时,下面的std::shared_ptrboost::shared_ptr类如何在python中以多态方式工作?

struct A
{
    virtual ~A() {}
};

struct B : A
{
    B() {}
    virtual ~B() {}
};

void f(const std::shared_ptr<A>& ptr)
{}

BOOST_PYTHON_MODULE(test)
{
    class_<A, boost::noncopyable>("A", no_init);

    class_<B, std::shared_ptr<B>, bases<A>>("B")
        .def(init<>());

    def("f", f);
}

我知道必须为boost::get_pointer定义std::shared_ptr方法,因此我确保在#include <boost/python.hpp>之前存在以下行:

namespace boost {
template<class T> const T* get_pointer(const std::shared_ptr<T>& p)
{
    return p.get();
}

template<class T> T* get_pointer(std::shared_ptr<T>& p)
{
    return p.get();
}
} // namespace boost

现在,在python中我尝试:

>>> from test import *
>>> b = B()
>>> f(b)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
ArgumentError: Python argument types in
    test.f(B)
did not match C++ signature:
    f(std::shared_ptr<A>)

注意:上面的代码适用于boost::shared_ptr,但我想坚持使用C ++ 11类型。

感谢。

2 个答案:

答案 0 :(得分:0)

Boost.Python内置了特殊魔法来识别boost :: shared_ptr。它目前不识别std :: shared_ptr。现在,只需皱眉并使用boost :: shared_ptr。

答案 1 :(得分:0)

我在编写时使用std::shared_ptr使用get_pointer与boost :: python IIRC一起工作。 (相关评论为here)。我的猜测是你需要class_<A,std::shared_ptr<A>,...>,因为这是你的函数作为参数。