如何实现“等于”模板函数? (谓词版本) [英] How is the 'equal' template function implemented? (predicate version)

查看:225
本文介绍了如何实现“等于”模板函数? (谓词版本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一本书Accelerated C ++,其中一个练习要求我们在头文件中模拟'equal'函数,到目前为止我已经实现了简单的版本,它接受三个参数,如下:

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?

推荐答案

第一个版本可以调用第二个版本,传递 equal_to 对象作为最后一个参数。 或者你可以将它设置为默认参数。我回来。我实际上不能找出一个方法来有一个功能模板的默认参数。我甚至不知道如何重用在重载解决方案中的代码,而不使用c ++ 0x功能(decltype)。

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)>());
}

这篇关于如何实现“等于”模板函数? (谓词版本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆