简体   繁体   English

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

[英]Using std::ptr_fun for a member function

Consider the following: 考虑以下:

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

The above code fails to negate the effect of is_odd() because it is a member function. 上面的代码无法否定is_odd()的影响,因为它是一个成员函数。 The call to std::ptr_fun() fails. std::ptr_fun()的调用失败。

How do I make it to work? 我该如何使它工作? Please note that I want is_odd() to be a non-static member function. 请注意,我希望is_odd()是一个非静态成员函数。

There are multiple issues with using A::is_odd(int) as a unary predicate, especially when it needs to be used with std::not1() : 使用A::is_odd(int)作为一元谓词存在多个问题,特别是当它需要与std::not1()

  1. A call to A::is_odd(int) takes two arguments: the implicit object (" this ") and the visible int argument. A::is_odd(int)调用有两个参数:隐式对象(“ this ”)和visible int参数。
  2. It isn't a function object defining argument_type and result_type . 它不是定义argument_typeresult_type的函数对象。

Properly using this member function as a unary predicate requires two steps: 正确使用此成员函数作为一元谓词需要两个步骤:

  1. Adapting the member function pointer to be a suitable function object, eg, using one of the std::mem_*fun functions. 使成员函数指针适合作为合适的函数对象,例如,使用std::mem_*fun函数之一。
  2. Binding the first argument to a suitable object, with a non-C++11 compiler probably using std::bind1st() . 使用非C ++ 11编译器将第一个参数绑定到合适的对象,可能使用std::bind1st()

With a C++11 compiler things are a lot easier because std::bind() take care of both of these. 使用C ++ 11编译器,事情要容易std::bind()因为std::bind()会处理这两个问题。 Assuming it is used from a member of A : 假设它是从A的成员使用A

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

The same with a pre-C++11 compiler is somewhat harder. 与C ++ 11之前的编译器相同有点困难。 The use in std::remove_if() would look something like this: 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());

Just make is_odd static, so it won't require an implicit this parameter: 只需使is_odd静态,所以它不需要隐式的this参数:

static bool is_odd(int i)

It doesn't use any member variables or other member functions anyway. 它无论如何都不使用任何成员变量或其他成员函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM