Friday, October 23, 2015

boost.python: how to bind member overloaded functions which semantic differs only by const?

Lets suppose we have class Test that we want export to python:
class CustomType
{
public:
    int m_value;
};

class Test
{
public:
    const CustomType & get_value() const { return m_value; }
    CustomType & get_value() { return m_value; }

private:
    CustomType m_value;
};
The piece of code that is below binds both overloads of get_value method:
void add_python_bidings_test( )
{
    class_< Test >( "Test" )
        .def( "get_value_const", ( const CustomType & (Test::*)() const) &Test::get_value,
        boost::python::return_value_policy<boost::python::copy_const_reference>( ))
        .def( "get_value", ( CustomType & (Test::*)() ) &Test::get_value,
        boost::python::return_value_policy<boost::python::copy_non_const_reference>( ) );
}
I compiled this only on Visual Studio compiler and didn't check inside python, however, I believe it should work. Please, let me know if you find any issues.