是否可以在数组中保存具有不同参数的成员函数?
Is it possible to hold member functions with different arguments in an array?
假设我有
void a::f1()
void a::f2(int)
void a::f3(const std::string&)
我是否可以使用数组来存储类似的东西
ary1 = {&a::f1, bind(&a::f2, 2), bind(&a::f3, "abc"}
ary2 = {&a::f1, bind(&a::f3, "def")}
只要可调用对象具有相同的签名,就可以在std::function
中存储不同的可调用对象,例如:
struct A {
void f1();
void f2(int);
void f3(const std::string&);
};
int main() {
std::function<void(A&)> functions[] = {
&A::f1
, [](A& a) { a.f2(2); }
, [](A& a) { a.f3("abc"); }
, std::bind(&A::f3, std::placeholders::_1, "abc")
};
A a;
for(auto& f : functions)
f(a);
}
请注意,我在这里使用了 lambda 表达式而不是std::bind
,因为 lambda 是最佳实践:更易于编写、阅读和更高效。
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 使用指向成员的指针将成员函数作为参数传递
- 如何将lambda作为模板类的成员函数参数
- 将成员函数指针作为参数传递给模板方法
- c++构造函数成员初始化:传递参数
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 模板化检查是否存在带有参数列表的类成员函数?
- 如何将类成员方法的参数列表自动填充写入可变参数?
- 为什么我需要在成员发起器列表中重复基类的模板参数?
- C++向量默认为成员参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 绑定到可变参数成员函数
- C/C++ 包含点的宏参数(成员访问运算符)
- 将const char * const参数成员分配给新值
- 基于模板参数成员函数参数的模板专用化
- 如何访问可变参数成员
- 可变类参数成员变量的异构存储
- 非模板类中的可变参数成员