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

时间:2015-12-17 10:49:57

标签: 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());
    }
};

上述代码无法否定is_odd()的影响,因为它是一个成员函数。对std::ptr_fun()的调用失败。

如何让它发挥作用?请注意,我希望is_odd()成为非静态成员函数。

2 个答案:

答案 0 :(得分:8)

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

  1. A::is_odd(int)的调用需要两个参数:隐式对象(&#34; this&#34;)和可见的int参数。
  2. 它不是定义argument_typeresult_type的函数对象。
  3. 正确使用此成员函数作为一元谓词需要两个步骤:

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

答案 1 :(得分:1)

只需将is_odd设为静态,因此不需要隐式this参数:

static bool is_odd(int i)

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