对成员函数使用std::ptr_fun

Using std::ptr_fun for a member function

本文关键字:ptr fun std 成员 函数      更新时间:2023-10-16

考虑以下内容:

class A
{
    public:
    bool is_odd(int i)
    {
        return (i % 2) != 0;
    }
    void fun()
    {
        std::vector<int> v2;
        v2.push_back(4);
        v2.push_back(5);
        v2.push_back(6);
        // fails here
        v2.erase(std::remove_if(v2.begin(), v2.end(), std::not1(std::ptr_fun(is_odd))), v2.end());
    }
};

上面的代码未能否定is_odd()的作用,因为它是一个成员函数。对std::ptr_fun()的调用失败。

我该如何上班?请注意,我希望is_odd()是一个非静态成员函数。

使用A::is_odd(int)作为一元谓词存在多个问题,尤其是当它需要与std::not1():一起使用时

  1. A::is_odd(int)的调用需要两个参数:隐式对象("this")和可见的int参数
  2. 它不是定义argument_typeresult_type的函数对象

正确使用此成员函数作为一元谓词需要两个步骤:

  1. 将成员函数指针适配为合适的函数对象,例如,使用std::mem_*fun函数之一
  2. 使用可能使用std::bind1st()的非C++11编译器将第一个参数绑定到合适的对象

使用C++11编译器,事情会容易得多,因为std::bind()同时处理这两个问题。假设它是从A的成员使用的:

... std::not1(std::bind(&A::is_odd, this, std::placeholders::_1)) ...

与C++11之前版本的编译器相同的情况有些困难。在std::remove_if()中的使用看起来像这样:

v2.erase(
    std::remove_if(v2.begin(),
                   v2.end(),
                   std::not1(std::bind1st(std::mem_fun(&A::is_odd), this))),
    v2.end());

只需使is_odd为静态,就不需要隐式this参数:

static bool is_odd(int i)

它不使用任何成员变量或其他成员函数。