【问题标题】:Boost.Python and Polymorphic Behaviour with std::shared_ptrBoost.Python 和 std::shared_ptr 的多态行为
【发布时间】:2012-04-28 16:28:00
【问题描述】:

我想知道下面的类AB 在使用std::shared_ptr 而不是boost::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);
}

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

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 类型。

谢谢。

【问题讨论】:

  • 如果其他人偶然发现了这一点,@eudoxos 有一个有效的解决方案,如下所示。你不需要切换到boost::shared_ptr

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


【解决方案1】:

Boost.Python 具有内置的特殊魔法来识别 boost::shared_ptr。它当前无法识别 std::shared_ptr。现在,只需皱眉并使用 boost::shared_ptr。

【讨论】:

  • Boost.python可以通过get_pointer使用std::shared_ptr,你写的不是真的。
  • std::shared_ptr 最近才受支持。在 boost 1.47 中它不存在。
【解决方案2】:

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

【讨论】:

  • 我试过class_&lt;A, std::shared_ptr&lt;A&gt;&gt;("A"),但没有运气。它编译得很好,但它在 python 中失败了。
  • 您真的发布了真实代码吗?如果不进行一些修改,我根本无法编译它。请问可以吗?
  • 我在 c++-sig 论坛 here 上发帖,因为它看起来像一个错误或至少是意外行为。让我们看看 boost:;python 家伙怎么说。
  • c++-sig here 有答案。总而言之,你必须说implicitly_convertible&lt;std::shared_ptr&lt;B2&gt;,std::shared_ptr&lt;A2&gt;&gt;();
猜你喜欢
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-01
  • 2013-06-12
  • 2013-04-16
  • 1970-01-01
  • 2014-01-03
相关资源
最近更新 更多