c++ - Boost.Python 和 std::shared_ptr 的多态行为

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

我想知道如何上课AB当使用 std::shared_ptr 时,下面可以在 python 中多态工作而不是 boost::shared_ptr

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

谢谢。

最佳答案

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

关于c++ - Boost.Python 和 std::shared_ptr 的多态行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10189426/

相关文章:

c++ - 使用具有多态性的引用时无效的初始化

c++ - int c=0 的结果; cout<<c++<<c;

c++ - 使用格式化结果解析搜索/替换头文件

c++ - memcpy 不复制到缓冲区

c++ - 使用带有初始化列表的 Stroustrup 的 PPP 书中的 vector 时出现编译错误

c++ - 由于模板基类,从不完整类型初始化静态 constexpr

c++ - 尝试使用unique_ptr的 vector 引用已删除的函数

c++ - 内存泄漏和多态性

c++ - 使用 Boost Coroutines 实现多任务调度器和执行器

c++ - 在 lambda 表达式中使用模板类方法时出现 GCC 编译错误