|
![](/i/fill.gif) |
Warp wrote:
> So-called functors are a common idiom in C++ template programming.
> For example many STL data containers and algorithms accept functors
> as parameters.
>
> A functor is something which acts like a function. In other words, it
> can be called like a function can be called, and it will return a value
> like a function returns a value.
>
> Obviously a regular function is a valid functor (and a common way to
> pass functors to the STL).
I see...
> Another way of creating a functor is, as you point out, to create a
> struct or class which has the operator() overloaded. This way an instance
> of that class can be used exactly like it was a function.
>
> The advantage of the latter method is that the struct/class can have
> member variables (and member functions) which the operator() can use.
> This way you can have different values for those member variables for
> different instances of the functor. (If I'm not completely mistaken,
> this starts get closer to so-called closures.)
Yes, indeed. It looks like that means you could do something like write
a struct that contains a number, and make it into a functor that adds
that number when called. OTOH, if your function really had to be a
*function*, you'd have to write a seperate function for every value you
might want to add... which would be, uh, silly.
In Haskell, you can just say "map (*2)" and it'll work. It looks like
what you're describing enables you to achieve something very similar in C++.
(Presumably the *other* thing about a C++ functor is that it could
change some internal state each time you call it - say, to generate
unique IDs or something...?)
> In the next C++ standard there will be a third type of functor: Lambda
> functions.
Knowing what I now know about C++ (constructors, copy constructors,
assignment constructors, pointers, references, etc.), I suspect this is
going to be... uh... "interesting". :-}
I wonder what the scoping rules would be like?
>> I'm almost tempted to try just to see if I can implement curried
>> functions with it in C++. You know, just to be totally perverse...
>
> C++ might not be the best language for that... ;)
Heh. It could probably work... but no, I'm sure it'll be pretty ugly.
;-) [Not to mention being abnormal C++ style.]
--
http://blog.orphi.me.uk/
http://www.zazzle.com/MathematicalOrchid*
Post a reply to this message
|
![](/i/fill.gif) |