467,878 Members | 1,263 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,878 developers. It's quick & easy.

[STL] using foreach in member function

Hello,

I wrote the following class:

class A {
//.. class description
};

class B {
void foo(A* a) {
//.. function description
}

void bar() {
for_each ( H->begin(), H->end(), &B::foo );
}

// member variable
vector<A*> *H; // initialize in elsewhere
}


In this case, the error message was
must use '.*' or '->*' to call pointer-to-member function in '__f (...)'
How can I call member function 'foo' in for_each command?

I aware that if function foo is the member function of class A, mem_fun should be used in for_each argument.
However, in my case, foo is the member function of class B. Is 'mem_fun' should used in this case?

In case of use mem_fun(&B::foo) instead of &B::foo, I got an error message;
argument of type 'void (H::)(A*) does not match 'void (H::*)(A*)'

I appreciate for your comment.
Aug 17 '09 #1
  • viewed: 4540
Share:
2 Replies
Expert 8TB
@church7
The third argument of the for_each template has to be an ordinary function (not a member function) or an object of a class that implements the operator() operator. Add an operator() operator that calls your function foo and you're done.

kind regards,

Jos
Aug 17 '09 #2
As a side note, you can use Boost.Foreach to greatly simplify your code by allowing you to use syntax similar to foreach in other languages.
You could do something like this:
vector<X> my_vect;
BOOST_FOREACH(const X& myvar, my_vect)
{
// do something with myvar, which is element of my_vect
}
Aug 17 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

30 posts views Thread by Przemo Drochomirecki | last post: by
9 posts views Thread by Aguilar, James | last post: by
13 posts views Thread by Park Ho-Kyung | last post: by
3 posts views Thread by pervinder | last post: by
12 posts views Thread by MuZZy | last post: by
7 posts views Thread by rodrigostrauss | last post: by
3 posts views Thread by Nelis Franken | last post: by
8 posts views Thread by kevin | last post: by
7 posts views Thread by ademirzanetti | last post: by
reply views Thread by MrMoon | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.