C++ or Python
mach.elf at gmail.com
Thu Jul 3 00:07:12 CEST 2008
2008/6/29 Dan Stromberg <dstromberglists at gmail.com>:
> On Sun, 29 Jun 2008 11:20:45 +0200, Sebastian \"lunar\" Wiesner wrote:
> > Dan Stromberg <dstromberglists at gmail.com>:
> >> things like passing a method as a function parameter is a no-brainer
> >> (requires extra syntax in java because of the cautious type system -
> >> not sure about C++).
> > C++ has function pointers and functors, therefore this is not really an
> > issue with C++.
> Based on http://en.wikipedia.org/wiki/
> Function_object#Functors_in_C_and_C.2B.2B it looks like there's no
> special syntax in the language core, but programs needing to pass an
> object as though it were a function (for example) do need to add some
> extra lines of code for each object needing such treatment.
That's a slightly different case - creating a functor in C++ is more
equivalent to making a Python object callable. Both require you to add
a specially named method to the class - "__call__" or "operator()".
The syntax for the pointer to the member function Bar of class Foo is
"&Foo::Bar", which is the same as taking a pointer to anything else in
The standard C++ library also has functions which take a pointer to a
member function and return a functor which can be used to call the
member function on an instance. (Whether passing the pointer as an
unbound method works correctly with functions which expect a reference
to a functor is compiler dependent, so is discouraged in portable
code) So it's quite easy to pass an unbound method in C++ - the only
extra line of code is #include<functional>. The disadvantage is that
member function pointers mostly behave like functors, except when they
don't, so there's more cognitive load.
What is a lot easier in Python is to pass a bound method as a
first-class function - you just use "instance.method_name" - but in
C++ there isn't a standard library function that takes an object
reference and a member function pointer and returns a functor bound to
that member. In the absence of automatic memory management, you have
to ensure the instance lifecycle exceeds the functor lifecycle, and
the standard library avoids making design decisions about lifecycles
of objects it doesn't create.
More information about the Python-list