You can use Boost.Bind as suggested by @ Space_C0wb0y. But if you cannot use this for any reason, then you can do something like this:
struct FooAggregator { typedef void (Foo::*Fun)(); void Boo() { CallForEach(m_foos.begin(), m_foos.end(), &Foo::Boo); } void Hoo() { CallForEach(m_foos.begin(), m_foos.end(), &Foo::Hoo); } template<typename FwdIterator> void CallForEach(FwdIterator first, FwdIterator last, Fun fun) { while (first != last ) { if(first->IsActivated()) { (first->*fun)(); } first++; } } };
Or you can use std::for_each from <algorithm> like:
#include <algorithm> struct FooAggregator { typedef void (Foo::*Fun)(); void Boo() { std::for_each(m_foos.begin(), m_foos.end(), Call(&Foo::Boo)); } void Hoo() { std::for_each(m_foos.begin(), m_foos.end(), Call(&Foo::Hoo)); } struct Call { Fun m_fun; Call(Fun fun) : m_fun(fun) {} void operator()(Foo & foo) { if(foo.IsActivated()) { (foo.*m_fun)(); } } }; };
Read the function object to understand the second example.
In C ++ 0x (i.e. C ++ 11) its very simple. You can use lamda in std::for_each like:
#include <algorithm> struct FooAggregator { void Boo() { std::for_each(m_foos.begin(), m_foos.end(), [](Foo &foo){ if (foo.IsActivated()) foo.Boo(); } ); } void Hoo() { std::for_each(m_foos.begin(), m_foos.end(), [](Foo &foo){ if (foo.IsActivated()) foo.Hoo(); } ); } //other code };
Nawaz source share