升压的Python:多态的容器? [英] Boost Python: polymorphic container?

查看:109
本文介绍了升压的Python:多态的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有它返回一个参考多态对象列表的方法(或功能):

I have a method (or function) which returns a reference to a list of polymorphic objects:

class A {

};
class B : public A {

};


std::list<boost::shared_ptr<A> >& getList();

如何在提振::蟒暴露这个功能,因此,在蟒蛇名单上迭代的时候,我会看到不同类型的 A 中和 B S'

推荐答案

首先,确保你的类确实是多态(即他们至少有一个虚函数或虚析构函数)。以上你的例子不对,但我敢肯定你的实际使用情况一样。如果没有,没有Boost.Python的年代RTTI基于机械多态性会工作。

First, make sure your classes are indeed polymorphic (i.e. they have at least one virtual function or a virtual destructor). Your example above doesn't, though I'm sure your real use case does. Without that none of Boost.Python's RTTI-based machinery for polymorphism will work.

然后,如果你已经暴露两类与Boost.Python的,注册的shared_ptr 为他们的转换器:

Then, if you've exposed both classes with Boost.Python and registered shared_ptr converters for them:

#include <boost/python.hpp>

namespace bp = boost::python;

BOOST_PYTHON_MODULE(example) {
    bp::class_<A >("A");
    bp::register_ptr_to_python< boost::shared_ptr<A> >();
    bp::class_< B, bp::bases<A> >("B");
    bp::register_ptr_to_python< boost::shared_ptr<B> >();
}

...这就是所有你需要做,以确保Python的永远只能看到最底层派生型。有没有必要做什么特别,确保 A 被强制转换为 B 如果可能的话。

...that's all you need to do to make sure Python only ever sees the most-derived type. There's no need to do anything special to ensure A is casted to B when possible.

这仍然留下了如何包装一个返回容器功能的问题。最简单的可能是使用附带Boost.Python的索引套件:

That still leaves the question of how to wrap a function that returns a container. The simplest is probably to use the indexing suite included with Boost.Python:

HTTP://www.boost。组织/ DOC /库/ 1_49_0 /库/蟒蛇/ DOC / V2 / indexing.html

有其他的选择浮动各地的网络(包括索引套件,在许多方面最好的一个2版,但不包括在Boost.Python的),但对于简单的问题,这可能是最方便

There are other options floating around the web (including a "version 2" of the indexing suite that is better in many respects, but isn't included with Boost.Python), but for simple problems this is probably the most convenient.

这篇关于升压的Python:多态的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆