我正在阅读《Accelerated C++》一书,其中一个练习要求我们模拟标题中的“equal”函数,到目前为止,我已经实现了采用三个参数的简单版本,如下所示:
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;
}
第二个版本可以接受第四个参数...
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;
}
我的问题是,这是理想的方法吗?或者这两个函数可以合并吗?
最佳答案
第一个版本可以调用第二个版本,传递equal_to对象作为最后一个参数。 或者您可以将其设置为默认参数。 我收回这句话。我实际上无法找到一种为函数模板提供默认参数的方法。我什至无法弄清楚如何在不使用 c++0x 功能(decltype)的情况下重用重载解决方案中的代码。
template <class iterType1, class iterType2>
bool cequal(iterType1 begin, iterType1 end, iterType2 e){
return cequal(begin, end, e, std::equal_to<decltype(*begin)>());
}
关于c++ - 'equal'模板函数是如何实现的? (谓词版本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4731007/