-
June 6th, 2012, 01:20 PM
#1
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.
-
June 6th, 2012, 02:12 PM
#2
Re: pointer to member function
-
June 7th, 2012, 03:17 AM
#3
Re: pointer to member function
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());
}
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|