[英]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()
:
A::is_odd(int)
takes two arguments: the implicit object (" this
") and the visible int
argument. A::is_odd(int)
调用有两个参数:隐式对象(“ this
”)和visible int
参数。 argument_type
and result_type
. argument_type
和result_type
的函数对象。 Properly using this member function as a unary predicate requires two steps: 正确使用此成员函数作为一元谓词需要两个步骤:
std::mem_*fun
functions. std::mem_*fun
函数之一。 std::bind1st()
. 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.