[C++-sig] Overloads.html

William Trenker wtrenker at hotmail.com
Mon Dec 16 21:43:06 CET 2002


What follows is my attempt to summarize the help I've received here on the 
subject of overloads.  Have I explained this appropriately?

Thanks,
Bill

===========================================================================

*

This is a variant of the example in overloads.html.  This example 
illustrates:
  - using casts instead of BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS()
  - overloading a member function

*/

#include <boost/python.hpp>
using namespace boost::python;

struct Y
{
    int f() { return 123; };
};
struct X
{
    Y& f(int x, double y = 4.25, char const* z = "wow")
    {
        return inner;
    }
    int f(int a, int b, int c) { return a + b + c; };
    Y inner;
};

BOOST_PYTHON_MODULE(args_ext)
{
    int (Y::*fy)() = &Y::f;
    class_<Y>("Y")
        .def("f", fy)
        ;

    Y& (X::*fx1)(int,double,char const*) = &X::f;
    int (X::*fx2)(int, int, int) = &X::f;
    class_<X>("X", "This is X's docstring")
        .def("f", fx1, "f's docstring",
                args("x", "y", "z"),
                return_internal_reference<>()
            )
        .def("f", fx2, args("a","b","c"))
        ;
};

/*

Notice that .def("f",fx2 ...) doesn't have a docstring.  Since Python can't 
overload functions or class members, only one specification of docstring can 
be used.  However, notice that each .def() for class_<X> does have different 
values for arg() which can be used in Python for keyword arguments.

The return_internal_reference<>() is essential because the .def() it is part 
of represents a function that returns a reference (i.e. Y&).

Pythonistas will find the idea of overloaded functions based on argument 
signatures a strange notion, but the above wrapper code actually makes the 
following possible:

---------------------------------------test.py----------------------------------------------
import args_ext

y = args_ext.Y()
print 'y.f() = %i' % y.f()

x = args_ext.X()
print 'x.f(5,4,3) = %i' % x.f(5,4,3)
print 'x.f(b=1,a=2,c=3) = %i' % x.f(b=1,a=2,c=3)

y = x.f(2,3.0,"hi")
print 'type(y) = %s' % type(y)
print 'y.f() = %i' % y.f()

--------------------------------------results------------------------------------------------
y.f() = 123
x.f(5,4,3) = 12
x.f(b=1,a=2,c=3) = 6
type(y) = <class 'args_ext.Y'>
y.f() = 123

*/


_________________________________________________________________
MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. 
http://join.msn.com/?page=features/virus





More information about the Cplusplus-sig mailing list