问题
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?
回答1:
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).
template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){
return cequal(begin, end, e, std::equal_to<decltype(*begin)>());
}
回答2:
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.
回答3:
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:
template<typename T1, typename T2>
struct eqpred
{
bool operator(T1 &a, T2 &b) { return a==b; }
}
template <class iterType1, class iterType2, class boolPred=eqpred>
bool cequal(iterType1 begin, iterType1 end, iterType2 e, boolPred pred){
while(begin != end){
if(!pred(*begin, *e))
return false;
++begin;
++e;
}
return true;
}
来源:https://stackoverflow.com/questions/4731007/how-is-the-equal-template-function-implemented-predicate-version