C++成员函数表

chr*_*isd 1 c++ arrays member-function-pointers data-structures

我需要一个将代码映射到C++成员函数的表.假设我们有这个类:

class foo
{
  bool one() const;
  bool two() const;
  bool call(char*) const;
};
Run Code Online (Sandbox Code Playgroud)

我想要的是这样一个表:

{
  { “somestring”,  one },
  { ”otherstring”, two }
};
Run Code Online (Sandbox Code Playgroud)

因此,如果我有一个foo对象f,f.call(”somestring”)将在表中查找"somestring",调用one()成员函数,并返回结果.

所有被调用的函数都有相同的原型,即它们是const,不带参数,返回bool.

这可能吗?怎么样?

Dre*_*ann 6

是的,可以使用指向成员语法的指针.

使用您提供的原型,地图将是.

std::map< std::string, bool( foo::*)() const>
Run Code Online (Sandbox Code Playgroud)

它将使用此语法调用

this->*my_map["somestring"]();
Run Code Online (Sandbox Code Playgroud)

这个奇怪的->*运算符用于指向成员函数的指针,由于继承,这可能有一些奇怪的考虑因素.(它不仅仅是一个原始地址,正如->所期望的那样)