Skip to main content
GameDev.net gamedev.net
🔒 Locked

std::mem_fun + boost::shared_ptr ???

Started by gimp Aug 8, 2002 at 4:48 AM 4 replies 3.1k views
Original Post
gimp
gimp
How would I write the syntax for this: std::for_each(m_PersistentEvents.begin(), m_PersistentEvents.end(), std::mem_fun(&CGameEvent::Execute)); Where m_PersistentEvents no longer is filled with pointers, but smart pointers? Error : ''std::mem_fun_t::operator`()'''' : cannot convert parameter 1 from ''boost::shared_ptr'' to ''CGameEvent *'' ..or is this a case of ''not unless you modify boost''? Many thanks, Chris Brodie http:\\fourth.flipcode.com
Chris Brodie
dalleboy
dalleboy
Use boost::mem_fn instead of std::mem_fun.


  

#include <vector>

#include <algorithm>

#include <boost/shared_ptr.hpp>

#include <boost/mem_fn.hpp>

class GameEvent
{
public:
void Execute()
{
}
};

int main()
{
std::vector<boost::shared_ptr<GameEvent> > oVector;
oVector.push_back(boost::shared_ptr<GameEvent>(new GameEvent()));
std::for_each(oVector.begin(), oVector.end(), boost::mem_fn(&GameEvent::Execute));

return 0;
}
gimp
gimp
Excellent advice. Thankyou. I appreciate the compilable example as well. Thanks.

Chris Brodie
http:\\fourth.flipcode.com
Chris Brodie
Fruny
Fruny
Or use boost::bind for more flexibility,

std::for_each(oVector.begin(), oVector.end(), boost::mem_fn(&GameEvent::Execute));

becomes

std::for_each(oVector.begin(), oVector.end(), boost::bind(&GameEvent::Execute, _1));

with _1 representing the first parameter that for_each passes to the functor (here, the this pointer).

I like boost::bind better, because it covers all possible combinations (member functions, member _variables_, regular functions ...).

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
sark
sark
Im with fruny on this one. boost::bind rocks. The _1 _2 substitution stuff may look strange at first but you get used to it.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.