我想知道如何上课A
和 B
当使用 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/