我需要一个将代码映射到C++成员函数的表。假设我们有这样一个类:
class foo
{
bool one() const;
bool two() const;
bool call(char*) const;
};我想要的是这样一张表:
{
{ “somestring”, one },
{ ”otherstring”, two }
};因此,如果我有一个foo对象字符串,f.call(”somestring”)将在表中查找“f”,调用one()成员函数,并返回结果。
所有被调用的函数都有相同的原型,即它们是const,不带参数,并且返回bool。
这个是可能的吗?多么?
发布于 2012-01-27 01:30:06
由于您只需要存储具有相同参数和返回类型的同一类的成员,因此可以使用指向成员函数的指针:
bool foo::call(char const * name) const {
static std::map<std::string, bool (foo::*)() const> table
{
{"one", &foo::one},
{"two", &foo::two}
};
auto entry = table.find(name);
if (entry != table.end()) {
return (this->*(entry->second))();
} else {
return false;
}
}它使用C++11的新初始化语法。如果你的编译器不支持它,还有其他各种选择。你可以用一个静态函数来初始化map:
typedef std::map<std::string, bool (foo::*)() const> table_type;
static table_type table = make_table();
static table_type make_table() {
table_type table;
table["one"] = &foo::one;
table["two"] = &foo::two;
return table;
}或者,您可以使用Boost.Assignment
static std::map<std::string, bool (foo::*)() const> table =
boost::assign::map_list_of
("one", &foo::one)
("two", &foo::two);或者,您可以使用一个数组,并使用std::find_if (如果您的库中还没有这样的数组,则使用一个简单的for循环)来查找条目,或者如果您确保数组已经排序,则使用std::binary_search查找条目。
发布于 2012-01-27 01:21:18
是的,可以使用指向成员语法的指针。
使用您提供的原型,映射将是。
std::map< std::string, bool( foo::*)() const>它将使用以下语法进行调用
this->*my_map["somestring"]();看起来奇怪的->*操作符用于指向成员函数的指针,由于继承,这可能会有一些奇怪的考虑因素。(这不仅仅是一个原始地址,正如->所期望的那样)
发布于 2012-01-27 01:19:57
是。
struct foo_method
{
std::string name;
bool (foo::*pfun)() const;
};
foo_method methodTable[] =
{
{ “somestring”, &foo::one },
{ ”otherstring”, &foo::one }
};
void foo::call(const char* name) const
{
size_t size = sizeof(methodTable)/sizeof(*methodTable);
for(size_t i = 0 ; i < size ; ++i)
{
if ( methodTable[i].name == name )
{
bool (foo::*pfun)() const = methodTable[i].pfun;
(this->*pfun)(); //invoke
}
}
}https://stackoverflow.com/questions/9022311
复制相似问题