[C++-sig] Static Methods

David Abrahams dave at boost-consulting.com
Mon Nov 4 21:11:53 CET 2002

Francois Ostiguy <ostiguy at fnal.gov> writes:

> Hi-
> In a message on this list on July 5, Dave Abrahams said:
> >We don't have a way to make true static methods yet.
> >getDims will work fine if you access it through the class like this:
> >
> >    Nums.getDims()
> >
> >but not if you access it through the instance
> >
> >    n = Nums()
> >    n.getDims() # error
> >
> >-Dave
> I am assuming that the above statement remains true for the newly
> released Boost.python v2.


> I am trying to wrap the a static function Ring::initNodes().  (For
> reference, Ring is a class that inherits virtually from other
> classes; I think this should be immaterial in the present context).


> When I import my module and try to run Ring::initValues(), here is what
> get
> >>> a = Ring()
> >>> Ring.initValues()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: type object 'orbit.Ring' has no attribute 'initValues'
> As it should be ... however
> >>> Ring.initNodes()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: unbound method Boost.Python.function object must be called with
> Ring instance as first argument (got nothing instead)
> What am I missing ?


You can make a static method from Python as follows:

    import hello
    # add a regular function to the World class as a static method
    hello.World.foo = staticmethod(hello.foo)
    x = hello.World('hi')
    print x.greet()  
    print hello.World.foo()
    print x.foo()

There's no reason we couldn't do this from C++; the biggest challenge
is deciding on an interface. For example, do we add a set of 3
overloads for class_<>::def_static(...) <ick>? Or, should we add an
additional overload to class_<>::def(...) which takes 4 parameters,
one of which may be `static_' <better>? Or should the interface be
something else?

                    David Abrahams
dave at boost-consulting.com * http://www.boost-consulting.com

More information about the Cplusplus-sig mailing list