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

C++ 使用std::ptr_fun作为成员函数,c++,c++03,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

考虑以下几点:

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());
    }
};
A类
{
公众:
布尔是奇数(int i)
{
返回(i%2)!=0;
}
虚无乐趣()
{
std::向量v2;
v2.推回(4);
v2.推回(5);
v2.推回(6);
//这里失败了
v2.擦除(std::remove_if(v2.begin()、v2.end()、std::not1(std::ptr_fun(is_odd))、v2.end();
}
};
上述代码无法否定
is_odd()
的效果,因为它是一个成员函数。调用std::ptr_fun()失败


我怎样才能让它工作?请注意,我希望
是非静态成员函数。

Just make
是非静态成员函数,因此它不需要隐式
参数:

static bool is_odd(int i)

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

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

  • 调用
    A::is_odd(int)
    需要两个参数:隐式对象(“
    this
    ”)和可见的
    int
    参数
  • 它不是定义
    参数类型
    结果类型
    的函数对象
  • 正确使用此成员函数作为一元谓词需要两个步骤:

  • 将成员函数指针调整为合适的函数对象,例如,使用
    std::mem_*fun
    函数之一
  • 使用非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());
    

    Make
    是一个静态函数吗?还是非成员函数?没有理由它应该是一个成员函数。@HappyCoder:那就让它成为一个静态成员函数吧。你可以自己编写一个类似于
    [this](int n){return is_odd(n);}
    类型的函子类,然后使用它。@KerrekSB注意
    is_odd()
    已经是我的类的一部分了。如果我创建一个函子类,并执行
    !is_odd()
    ,我需要
    A
    的对象。如果没有,就会有代码重复(
    is_odd
    只是一个例子,实际代码实际上是巨大的)使用functor实现
    A::is_odd
    ,从而避免代码重复。我没有注意到它是从
    a
    的成员调用的。我更新了答案。谢谢