0
点赞
收藏
分享

微信扫一扫

C++之仿函数

yongxinz 2023-06-25 阅读 52

仿函数:函数对象;

仿函数(functors)其实就是重载了operator()的对象

#include <iostream>
using namespace std;

template<typename T>
struct m_plus
{
    T operator()(const T& x, const T& y) { return x + y; }
};

int main(int argc, char *argv[])
{
    // 定义其对象  调用其operator()
    m_plus<int> op;
    cout << op(1, 2) << endl;
    // 产生一个匿名对象  这是仿函数的主流用法
    cout << m_plus<int>()(1, 2) << endl;
    return 0;
}



1.仿函数可以有自己的状态,而函数指针则不行(有的使用template或者static变量可以实现)。

我们可以这样子使用仿函数:

#include <iostream>
using namespace std;

template<typename T, T add>
struct m_plus
{
    m_plus() { _add = add; }
    T operator()(const T& x) { return x + _add; }
    // 仿函数可以具有自己的状态
    int _add;
};

int main(int argc, char *argv[])
{
    m_plus<int, 10> op;
    cout << op(100) << endl;
    cout << op(200) << endl;
    return 0;
}



2.仿函数可以与函数适配器搭配使用。

举一个例子,例如我们如果要使用count_if算法来计算容器中大于10的元素的个数。

如果我们使用greater<int>作为判别式(二元),而count_if只接受一个一元判别式,这时候我们就需要搭配函数适配器一起使用了。

而函数指针不能直接搭配函数适配器一起使用,具体在分析bind2nd的时候会讲到。

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;


int main(int argc, char *argv[])
{
    vector<int> coll{ 1, 3, 5, 7, 9, 11, 13, 15 };
    // 接着下面有bind2nd的具体实现
    cout << count_if(coll.begin(), coll.end(), bind2nd(greater<int>(), 10)) << endl;
    return 0;
}





举报

相关推荐

0 条评论