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

Cin*_*out 8 c++ c++03

考虑以下:

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());
    }
};
Run Code Online (Sandbox Code Playgroud)

上面的代码无法否定is_odd()因为它是成员函数的影响.呼叫std::ptr_fun()失败.

我该如何使它工作?请注意,我想is_odd()成为非静态成员函数.

Die*_*ühl 8

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

  1. 调用A::is_odd(int)带有两个参数:隐式对象(" this")和可见int参数.
  2. 它不是定义argument_type和的函数对象result_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)) ...
Run Code Online (Sandbox Code Playgroud)

与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());
Run Code Online (Sandbox Code Playgroud)