使用 std::ptr_fun 作为成员函数

Using std::ptr_fun for a member function

考虑以下几点:

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() 成为非静态成员函数。

只需将 is_odd 设为静态,这样就不需要隐式 this 参数:

static bool is_odd(int i)

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

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

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

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

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

有了 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());