用于成员函数映射的c++find()
c++ find() for map of member function
我有两个具有继承性的类。我想允许这些类将它们的函数存储在一个映射中。如何通过键创建查找功能?函数的继承会起作用吗(MyClass_2没有自己的doSmth()函数,它应该添加MyClass中的doSmh())?我的尝试如下。:
template<class T>
class Class1
{
typedef void(T::*MyFunction)();
map<string, MyFunction> functionMap;
public:
void addFunc(string funcName, MyFunction function) {
functionMap.insert(pair<string, MyFunction>(funcName, function));
}
bool findFunc(string key) {
typename map<string, MyFunction>::iterator it;
it = functionMap.find(key.c_str());
}
};
class MyClass {
Class1<MyClass> class1;
void addFunc() {
class1.addFunc("Func1", &MyClass::doSmth);
}
void findAndCallFunc(string key) {
class1.findFunc(key);
}
void doSmth();
};
class MyClass_2: MyClass {
Class1<MyClass_2> class1;
void addFunc() {
class1.addFunc("Func1", &MyClass_2::doSmth);
}
}
编辑:我测试了我的程序。它有效。我的问题是,如果我从MyClass_2的对象调用fundAndCallFunc。它不是MyClass_2的class1,而是MyClass的class1。我应该更改什么?
正如Chris所说,findFunc
应该返回实际函数:
MyFunction findFunc(string key)
{
const map<string, MyFunction>::const_iterator it = functionMap.find(key);
return it == functionMap.end() ? NULL : it->second;
}
此外,如果只将函数指针存储到成员函数,则会丢失对实际对象的跟踪(因此,您可以将映射设置为静态!)。也许你还应该存储对象的this
指针,也就是说,把你的地图做成这样:
std::map<std::string, std::pair<T*, MyFunction> > functionMap;
在addFunc
中,你会说
functionMap.insert(std::make_pair(funcName, std::make_pair(this, function)));
用法:假设it = functionMap.find("key")
。然后你可以说:
MyClass * const p = it->second.first;
MyFunction f = it->second.second;
p->*f(); // invoke -- yes, it's operator->*() in action
这里有两个显而易见的问题:
-
你的
findFunc
方法只是查找函数,它对它不做任何事情(试图调用它或返回方法指针),它被声明为返回bool
而不是MyFunction
——不确定你想让它做什么 -
您的
doSmth
方法在MyClass中是私有的,因此您无法在MyClass_2中访问它。您需要将其保护或公开。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 如何从多映射中删除特定的重复项
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- 为什么要对 map::find 应用不存在的键将返回一个C++中第一个值映射大小的迭代器
- 在无序映射<字符串上使用 find(),向量<string>>与 C++ 中的有序映射花费相同的时间
- 多映射less_equal导致错误的 find() 结果
- 使用结构作为映射的键和值.find() 操作给出错误
- C++stl::使用结构映射find
- 如何在int,string类型的映射上使用find
- 用于成员函数映射的c++find()