kle*_*vre 5 c++ algorithm foreach
我想知道是否有办法使用std :: mem_fun传递参数?我想确切地说,我可以拥有尽可能多的参数和许多成员函数.
问题是我的标准很旧而且我正在寻找一个完整的标准方式,因此即使我知道我可以轻松地做到这一点,也不允许提升作为答案= /
以下是我想如何使用它的一个小例子:
#include <list>
#include <algorithm>
// Class declaration
//
struct Interface {
virtual void run() = 0;
virtual void do_something(int) = 0;
virtual void do_func(int, int) = 0;
};
struct A : public Interface {
void run() { cout << "Class A : run" << endl; }
void do_something(int foo) { cout << "Class A : " << foo << endl; }
void do_func(int foo, int bar) { cout << "Class A : " << foo << " " << bar << endl; }
};
struct B : public Interface {
void run() { cout << "Class B : run" << endl; }
void do_something(int foo) { cout << "Class B : " << foo << endl; }
void do_func(int foo, int bar) { cout << "Class B : " << foo << " " << bar << endl; }
};
// Main
//
int main() {
// Create A and B
A a;
B b;
// Insert it inside a list
std::list<Interface *> list;
list.push_back(&a);
list.push_back(&b);
// This works
std::for_each(list.begin(), list.end(), std::mem_fun(&Interface::run));
// But how to give arguments for those member funcs ?
std::for_each(list.begin(), list.end(), std::mem_fun(&Interface::do_something));
std::for_each(list.begin(), list.end(), std::mem_fun(&Interface::do_func));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ork 11
使用std::bind通过std::bind1st和std::bind2nd
std::for_each(list.begin(), list.end(),
std::bind2nd(std::mem_fun(&Interface::do_something),1) // because 1st is this
);
Run Code Online (Sandbox Code Playgroud)
不幸的是,该标准对两个参数版本没有帮助,你需要编写自己的:
struct MyFunctor
{
void (Interface::*func)(int,int);
int a;
int b;
MyFunctor(void (Interface::*f)(int,int), int a, int b): func(f), a(a), b(b) {}
void operator()(Interface* i){ (i->*func)(a,b);}
};
std::for_each(list.begin(), list.end(),
MyFunctor(&Interface::do_func, 1, 2)
);
Run Code Online (Sandbox Code Playgroud)