boost-python select between overloaded methods

后端 未结 4 1986
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 21:38

Assume exist some class Foo with two overloaded methods:

class Foo
{
  ...
   void m1(A& a);
   void m1(B& b);

I need expose one of

4条回答
  •  不知归路
    2021-01-03 22:32

    While the other answers are correct there is no need to do any shenanigans with temporary variables or static_cast.

    The def function prototypes look like this:

    template 
    class_& def(char const* name, Fn fn);
    template 
    class_& def(char const* name, Fn fn, A1 const&);
    template 
    class_& def(char const* name, Fn fn, A1 const&, A2 const&);
    template 
    class_& def(char const* name, Fn fn, A1 const&, A2 const&, A3 const&);
    

    As you can see the first template parameter (Fn) is the type of the function pointer you want to wrap. Usually, all the template parameters are deduced by the compiler for you. However, if there is an ambiguity you need to help the compiler. If the function pointer is ambiguous due to an overloaded function you have to provide the proper type explicitly. In your case:

    boost::python::class_("Foo")
        .def("m1", &Foo::m1)
        .def("m1", &Foo::m1)
        ;
    

    Simple, isn't it? No need to cast or capture outside. The same thing is valid for creating free standing function at the module level, i.e. using boost::python::def.

提交回复
热议问题