2016-04-25 68 views
2

我有一個看起來像這樣的OO模式:在Boost Python中公開模板化基類的最佳方式?

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

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

class SomeOtherClass 
{}; 

class SecondDerived : public Derived<SomeOtherClass> 
{}; 

我有一個從一堆其他類的派生繼承許多類。我試圖找出將所有這些不同的「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如果這是真的,如果不是那麼應該足以解決我的問題,但我想知道是否有更好的方法來做到這一點?

回答

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) 
;