我想知道如何使用std::shared_ptr
而不是boost::shared_ptr
在下面的類A
和B
python多態工作?Boost.Python和多態行爲與std :: 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);
}
我知道,必須爲std::shared_ptr
定義的boost::get_pointer
方法,所以我一#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類型。
謝謝。
如果有人絆倒了這一點,@eudoxos在下面有一個工作解決方案。你不需要切換到'boost :: shared_ptr'。 – 2015-05-21 15:41:41