how to call member function in for_each?

Hi all,

How can i pass a member function in a for_each? I tried this so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//model.hpp
#ifndef MODEL_HPP
#define MODEL_HPP

#include <vector>

class model_listener;


class model {
	
public:
	model( );
	void add_listener( model_listener* );
protected:
	void notify_listeners( );
	void notify( model_listener* );
private:
	std::vector<model_listener*> *listeners;
};


class model_listener{
	
public:
	virtual void update_view(  ) = 0;
};
#endif 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//model.cpp
#include <algorithm>
#include <functional>

#include "model.hpp"

model::model( ) {
	listeners = new std::vector<model_listener*>;
}

void model::add_listener( model_listener* l ) {
	listeners -> push_back( l );
}

void model::notify_listeners(){
	std::for_each( listeners->begin(), listeners->end(), model::notify );
}

void model::notify( model_listener* l ) {
	l->update_view( );
}


I get this error from the compiler:
1
2
3
4
5
6
7
/usr/include/c++/4.4/bits/stl_algo.h: In function ‘_Funct std::for_each(_IIter, _IIter, _Funct)
 [with _IIter = __gnu_cxx::__normal_iterator<model_listener**, 
std::vector<model_listener*, 
std::allocator<model_listener*> > >, _Funct = void (model::*)(model_listener*)]’:
src/model.cpp:15:   instantiated from here
/usr/include/c++/4.4/bits/stl_algo.h:4200: error:
 must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘__f (...)’, e.g. ‘(... ->* __f) (...)’


I don't understand what the compiler is trying to say.

regards, hannesvdc
The for_each function has to make a call to the model::notify - which
unfortunately is a protected member function to which the for_each function will have no access and also the model::notify would need an object of type model to operate on.

As it looks like the model::notify function does not need access to any members of the model class anyway - just make it a public static member function.
Last edited on
It's some matter with how to use member function in for_reach. You can get some stuff by searching google.

Try.

#include <functional>

using namespace std;

std::for_each( listeners->begin(), listeners->end(), bind1st(mem_fun(&model::notify), this) );


b2ee
bind1st, mem_fun, bind2nd, mem_fun_ref, ptr_fun are all related. Do explore those standard functions in C++ STL.
Topic archived. No new replies allowed.