在Boost Python中公开模板化基类的最佳方法?

时间:2016-04-25 22:13:34

标签: python c++ boost

我有一个看起来像这样的OO模式:

class Base
{/*some pure virtual functions*/};

template < typename T>
class Derived : public Base
{/*some pure virtual functions*/};

class SomeOtherClass
{};

class SecondDerived : public Derived<SomeOtherClass>
{};

我有很多类继承自Derived和其他一些类。我试图弄清楚将所有这些不同的“SecondDerived”类暴露给Python的最简洁方法是什么。 Boost要求暴露基类。到目前为止,我已经提出了一种体面的方式来公开所有常见的成员函数:

// This is a templatized utility function that can do the most common expose operations
template < class SecondDerivedType, class TemplateParamter>
object create_secondderived_type()
{
    // first expose the Derived<SomeOtherClass> class
    object obj_base = class_<Derived<TemplateParameter>, bases<Base>> (name, no_init);

    // then the actual class may be exposed
    object obj_class = class_<SecondDerivedType, bases<Derived<TemplateParameter>>>(other_name)
        .def("common_function", &SecondDerivedType::common_function)
        ;

    // then you can return the object, but it seems to have little value
    return obj_class;
}


BOOST_PYTHON_MODULE(mymodule)
{
    // Within Boost Python, you just call the function with the templated arguments.
    object obj = create_secondderived_type<SecondDerived, SomeOtherClass>();
}

我遇到的问题是类似SecondDerived的类可能有我自己想要公开的成员函数,但到目前为止我对Boost Python的理解是你需要公开所有的成员函数一气呵成。我已经问here这是否属实,如果不是,那应该足以解决我的问题,但我想知道是否有更好的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

正如我对您的其他问题的回答一样,请不要返回object - 返回正确的class_专长:

template < class SecondDerivedType, class TemplateParamter>
class_<SecondDerivedType, bases<Derived<TemplateParameter>>>
create_secondderived_type()
{
    // first expose the Derived<SomeOtherClass> class
    object obj_base = class_<Derived<TemplateParameter>, bases<Base>> (name, no_init);

    // then the actual class may be exposed
    auto derived = class_<SecondDerivedType, bases<Derived<TemplateParameter>>>(other_name)
        .def("common_function", &SecondDerivedType::common_function)
        ;

    return derived;
}

然后你可以添加你想要的任何成员函数:

create_secondderived_type<SecondDerived, SomeOtherClass>()
    .def("specific_function", &SecondDerived::specific_function)
;