【发布时间】:2023-03-22 03:47:01
【问题描述】:
我想知道是否有办法使用 std::mem_fun 传递参数?
我想明确一点,我可以有尽可能多的参数和很多成员函数。
问题是我采用的是旧标准,我正在寻找一种完整的 stl 方式,因此即使我知道我可以轻松做到,也不允许将 boost 作为答案 =/
这是我想如何使用它的一个小例子:
#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;
}
【问题讨论】: