pointer to member function
Hello,
I am trying to use "remove_if" with a predicate function inside a class. The code intends to remove the grid cells which an agent cannot move into (from among all possible cells).
Code:
void classname::function1()
{
vector<MoorePoint> neighbors;
....
neighbors.erase(std::remove_if(neighbors.begin(),neighbors.end(),&classname::cannotMoveIn), neighbors.end());
...
}
bool classname::cannotMoveIn(MoorePoint mp)
{
return !mp.inGridNotOccupied;
}
That code would work if it was not in a class and the predicate was not a member function. However, now I receive long error messages which I guess refer to incompatibility of remove_if template with the predicate parameter (one error includes : error C2064: term does not evaluate to a function taking 1 arguments).
Does anyone have any idea what is wrong?
Thanks.
Re: pointer to member function
Re: pointer to member function
Quote:
Originally Posted by
sarmadys
That code would work if it was not in a class and the predicate was not a member function. However, now I receive long error messages which I guess refer to incompatibility of remove_if template with the predicate parameter (one error includes : error C2064: term does not evaluate to a function taking 1 arguments).
That's because member functions have an implicit first argument, which is the this pointer. So, to call a member function, you need an instance of the class to call it on.
Given that your function does not use any class members you can also make the function a static member, or use a global function (possibly in an anonymous namespace), or use locally defined function object - see below -, or use a lambda function if your compiler supports it.
Code:
void classname::function1()
{
vector<MoorePoint> neighbors;
//....
struct {
bool operator ()(const MoorePoint& mp) const {
return !mp.inGridNotOccupied;
}
} cannotMoveIn;
neighbors.erase(std::remove_if(neighbors.begin(), neighbors.end(), cannotMoveIn), neighbors.end());
}