I am working through the book "Accelerated C++" and one of the exercises require us to emulate the 'equal' function in the header and so far I have implemented the simple version which takes three parameters as follows:
template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){
while(begin != end){
if(!(*begin == *e))
return false;
++begin;
++e;
}
return true;
}
and the second version which can accept a fourth parameter...
template <class iterType1, class iterType2, class boolPred>
bool cequal(iterType1 begin, iterType1 end, iterType2 e, boolPred pred){
while(begin != end){
if(!pred(*begin, *e))
return false;
++begin;
++e;
}
return true;
}
My question is, is this the ideal way to do it? or are these two functions mergable?
Those two functions aren't just mergeable, they're almost exactly the same, line for line.
I could expand and do it all for you, but that would be a bit of a spoiler.
If you want to merge them, you could provide a default predicate for the last parameter that only calls
operator==
on the inputs.edit: an example would be:
The first version can call the second version, passing an equal_to object as the last parameter.
Or you can just set that as a default parameter.I take that back. I can't actually figure out a way to have a default argument for a function template. I can't even figure out how to re-use the code in the overload solution without using a c++0x feature(decltype).