TW, are C++ functors lke closures in other languages? Like
"frozen" functions?
Sort of. You can make something that is very close to a closure (ahem)
with a functor. You can also use them to do something similar to
currying.
struct power {
power( float second ) m_pow( second ) {}
float operator()( float first ) const { return std:

owf( first,
m_pow ); };
private:
float m_pow;
};
power now acts like a curried version of std:

owf - although beware,
I'm binding the second argument not the first so in a language like
Haskell you'd need to use flip too.
power cube( 3 );
cube( 10 ); // Will return 1,000
Note that the implementation of power uses what could be seen as a
closure. In C++ you don't get automatic closure of arguments within
the same lexical scope. You have to put them into the closing
structure yourself.
All of this is much clearer using Boost.Function and Boost.Lambda
where you can play with functional idioms more easily.
If you want to see this sort of thing in action, consider a function
for executing some script and returning a result. The lambda that will
execute the script has this type:
boost::function< _variant_t ( wstring ) >
This means that it takes a wstring (the source) and produces a
_variant_t (a wrapper for the Windows COM type VARIANT) which is the
result of the script execution.
Now to store a context for dynamic execution of a script I have this:
class Translator { // Creates HTML from some internal format
// snip
boost::function< _variant_t ( wstring ) > dynWriter;
};
I initialise this through a function that looks like this (abridged
slightly to make it clearer what is going on from some code for a
multi-threading JavaScript host):
boost::function< _variant_t ( wstring ) > embed() {
boost::shared_ptr< Mahlee > mahlee( new Mahlee );
return boost::lambda::bind(
&Mahlee::run,
boost::lambda::bind(
&boost::shared_ptr< FSLib:

rocess::Mahlee >::get,
mahlee ),
boost::lambda::_1 );
}
The first line creates a JavaScript interpreter and puts it into a
shared_ptr. For the lambdas it makes two. The inner one simply creates
a closure around the mahlee object and allows us to get the object
pointed to through the shared_ptr's get member.
The outer lambda then creates a functor object that embeds the
following:
mahlee->run( _1 )
This is stored in the dynWriter member earlier:
dynWriter = embed();
Now dynWriter has become a function that given some JavaScript
executes it and returns the result of the code into a _variant_t:
dynWriter( L"function() { return 'Hello world!'; }()" );
This will return a _variant_t with the string Hello world! in it.
The hardest part doing this in C++ is that you have to be very careful
to think through the full implications of object lifetimes. You can
see a more advanced use that shows the difference between generalised
partial application and currying on the second half of this page from
my web site:
http://www.kirit.com/News:/1720702
K