用于成员函数映射的c++find()

c++ find() for map of member function

本文关键字:c++find 映射 成员 函数 用于      更新时间:2023-10-16

我有两个具有继承性的类。我想允许这些类将它们的函数存储在一个映射中。如何通过键创建查找功能?函数的继承会起作用吗(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中访问它。您需要将其保护或公开。