在向量中存储特定类的成员函数的语法是什么?
What is the syntax for storing a specific class's member functions in a vector?
我做了相当多的搜索,但是*()和类作用域的组合极大地阻碍了我对语法的理解,每次编辑都会抛出一个新的错误,有什么帮助吗?
我想做什么:
声明一个指向MyClass.h
中成员函数指针的std::vector将实际成员函数赋值给MyClass.cpp构造函数中的std::vector
成员函数不是static
谢谢!
我很好奇你将从哪里使用它们。您可以看到,为了调用一个c++类成员函数,您需要有一个实例指针来调用它(每个成员函数都需要一个this来访问类状态)。通常你会用std::bind将成员函数指针和实例指针包装在一起,然后可能将结果存储在std::function中。要把它们化成向量,它们都需要相同的签名。
这是你要找的东西吗?
class P
{
typedef std::function<void (void)> func_t;
std::vector<func_t> functions;
public:
P()
{
functions.push_back(std::bind(&P::foo1, this));
functions.push_back(std::bind(&P::foo2, this));
functions.push_back(std::bind(&P::foo3, this));
}
void foo1(void)
{
std::cout << "foo1n";
}
void foo2(void)
{
std::cout << "foo2n";
}
void foo3(void)
{
std::cout << "foo3n";
}
void call()
{
for(auto it = functions.begin(); it != functions.end(); ++it)
{
(*it)();
}
}
};
int main()
{
P p;
p.call();
}
在OP进一步澄清后,我将提出以下建议:
class P
{
typedef std::function<void (void)> func_t;
std::map<const char*, func_t> functions;
public:
P()
{
functions["foo1"] = std::bind(&P::foo1, this);
functions["foo2"] = std::bind(&P::foo2, this);
functions["foo3"] = std::bind(&P::foo3, this);
}
void foo1(void)
{
std::cout << "foo1n";
}
void foo2(void)
{
std::cout << "foo2n";
}
void foo3(void)
{
std::cout << "foo3n";
}
void call_by_name(const char* func_name)
{
functions[func_name]();
}
};
int main()
{
P p;
p.call_by_name("foo1");
p.call_by_name("foo2");
p.call_by_name("foo3");
}
可以像这样使用成员函数指针(c++ 11与这部分无关):
struct S {
int foo(){std::cout<<"foo"; return 0;}
int bar(){std::cout<<"bar"; return 0;}
};
int main() {
std::vector<int(S::*)()> funcs{&S::foo, &S::bar};
S s;
for (auto func : funcs) {
(s.*func)();
}
}
然而,如果你使用c++ 11, std::function
可以使它更简洁:
std::vector<std::function<int(S &)>> funcs{&S::foo, &S::bar};
S s;
for (auto func : funcs) {
func(s);
}
如果您使用c++ 03, Boost有boost::function
,这是类似的
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法