Re: why aren't comparators passed as refs or c-refs in algorithms?
On 20 Jul., 06:44, "Hicham Mouline" <hic...@mouline.org> wrote:
Hello
if you take for example:
template<class ForwardIterator, class Compare>
ForwardIterator min_element(ForwardIterator first, ForwardIterator last,
Compare comp);
I am curious why hasn't been chosen to be passed as:
template<class ForwardIterator, class Compare>
ForwardIterator min_element(ForwardIterator first, ForwardIterator last,
const Compare& comp);
or a version without const?
This was an intentional design. In general, a call-by-value approach
has the effect that it allows better optimizations because it reduces
the chance of indirect calls. Vandevoorde/Josuttis describe that in
more detail in "C++ Templates: The Complete Guide" (sorry, I have
the book not on my desk and cannot quote the precise section).
I guess this is more restrictive, but I have in mind the cost of passing
the
comparator by value instead of by reference.
Typically there is no additional cost, because many function object
types are empty class types. If they are not, you can simply
change that e.g. by providing boost::reference_wrapper or
std::reference_wrapper (as of C++0x) instead.
I am writing a somehow generic member function template that returns the
max
element of a container based on the comparator, should I just do like STL?
I strongly suggest to follow this approach unless it is very
important that the caller object should keep state. A notable
exception from the general rule is the algorithm std::random_shuffle
with a third parameter (and the new algorithm std::shuffle in
C++0x).
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]