thinktwice wrote:
here is what i what to do;
//pesudo code
iter = container.begin();
while (iter != container.end())
{
myclass *obj =my_cast (*iter);
obj->func(arg1, arg2);
}
i want to simplify those code just like this:
std::for_each(conatiner.begin(), conatiner.end(), ???)
is it possible? how to achieve?
It's possible if you write your own functor. The standard means only
exist for no- and one-argument member functions.
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
struct foo {
void bar(int one, double two) {
cout << this << " : " << one << " and " << two << endl;
}
};
template<class T, class A1, class A2> struct mem_fun_2_t {
void (T::*memptr)(A1, A2);
A1 arg1;
A2 arg2;
mem_fun_2_t(void (T::*mp)(A1, A2), A1 a1, A2 a2)
: memptr(mp), arg1(a1), arg2(a2) {}
void operator()(T& t) { return (t.*memptr)(arg1, arg2); }
};
template<class T, class A1, class A2>
mem_fun_2_t<T,A1,A2> mem_fun_2(void (T::*mp)(A1, A2), A1 a1, A2 a2)
{
return mem_fun_2_t<T,A1,A2>(mp, a1, a2);
}
int main()
{
vector<foo> v(10);
for_each(v.begin(), v.end(), mem_fun_2(&foo::bar, 42, 3.14159));
}
-----------------
There is probably a nicer solution in Boost, but I don't know it and
I am too lazy to look for it.
V
--
Please remove capital As from my address when replying by mail