четвртак, 5. јануар 2012.

Functors: Function Objects in C++

support functionpointers, which provide a way to pass around instructions on how toperform an operation. But function pointers are limited becausefunctions must be fully specified at compile time. What do I mean? Let's saythat you're writing a mail program to view an inbox, and you'd like to givethe user the ability to sort the inbox on different fields--to, from, date,etc. You might try using a sort routine that takes a function pointer capableof comparing the messages, but there's one problem--there are a lot ofdifferent ways you might want to compare messages. You could create differentfunctions that differ only by the field of the message on which the comparisonoccurs, but that limits you to sorting on the fields that have been hard-codedinto the program. It's also going to lead to a lot of if-then-else blocksthat differ only by the function passed into the sort routine.



What you'd really like is the ability to pass in a third argument to yourcomparison function, telling it which field to look at. But to make thiswork, you'd have to write your own sort routine that knows about the thirdargument; you can't use a generic routine like the STL's sort function becauseyou can't tell it to pass in a third argument to the comparator. Instead, yousomehow need the ability to "embed" what field to sort on inside the function.

It turns out that you can get this behavior in C

View the Original article

Нема коментара:

Постави коментар