仿函数

仿函数:先了解一下为什么需要“仿函数”

考虑将函数指针做为函数 A 的形参的情况下,假如需求变更,需要修改函数指针的签名。这种情况下,在修改函数指针声明之后,还必须修改函数 A

“仿函数”的存在目的,就是我们希望不修改函数 A,仍然可以实现函数签名的变更。

C++ 仿函数_恋喵大鲤鱼的博客-CSDN博客

 

仿函数的特点

仿函数(functor)是一个能行使函数(function)功能的类对象(class object)。

所以,他首先是一个,然后需要对类重载操作符()

稍微拓展一下,类也可以变成是一个模板类

 

例程

class myFunctor
{
public:
    myFunctor() {}
    bool operator()(int a) const
    {
        return a > 10;
    }
};


// We do not want to change this function
void printValueOver10(const std::vector<int>& data, myFunctor fun)
{
    for (auto a : data)
    {
        if (fun(a))
            std::cout << a << std::endl;
    }
}


int main()
{
    printValueOver10({1,50,10,20}, myFunctor());

    return 0;
}

如果现在需要变更myFunctor,可以这样做

class myFunctor
{
public:
    myFunctor(int val) { m_val = val; }
    bool operator()(int a) const
    {
        return a > m_val;  // Modify the () function
    }
    int m_val = 10;        // Add variables here
};


// We do not want to change this function
void printValueOver10(const std::vector<int>& data, myFunctor fun)
{
    for (auto a : data)
    {
        if (fun(a))
            std::cout << a << std::endl;
    }
}


int main()
{
    printValueOver10({1,50,10,20}, myFunctor(20));

    return 0;
}

 

posted @ 2023-07-07 14:33  路边的十元钱硬币  阅读(24)  评论(0编辑  收藏  举报