使用std::function存储继承类的方法c++

Using std::function to store methods of inherited classes c++

是否可以这样做?:

// some_header.hpp
#ifndef SOME_HEADER_HPP
#define SOME_HEADER_HPP

class baseclass
{
public:
    baseclass(){};
    std::map<std::string, std::function<void()>> methods_map;
    void call_method(const std::string &name){
        auto it = methods_map.find(name);
        if(it != methods_map.end())
            it->second();
        else std::cout << "Method " << name << " not exists";
    }
};
#endif

比main.cpp

#include "some_header.hpp"

class inherited : public baseclass{
public:
   inherited():baseclass(){};   
   void new_meth(){
      std::cout << "Hello, Whosebug!";
   }
};

int main(){
   std::vector<baseclass*> objects;
   auto temp = new inherited();
   objects[0].methods_map["new"]=&temp->new_meth;
   objects[0].call_method("new");
}

这个变体不起作用,无法创建指向成员函数的非常量指针 所以,我的问题是:是否可以这样做以及如何做?

你很接近:&temp->new_meth 无效,你可以通过以下方式之一将 temp 捕获到 void() 函子中:

objects[0]->methods_map["new"] = std::bind_front(&inherited::new_meth, temp);
objects[0]->methods_map["new"] = [&] { return temp->new_meth(); }

备注:

  • objects[0] 是无效索引,因为您从未向该向量中插入任何内容;
  • objects[0] 是一个指针,所以你需要用 ->;
  • 取消引用它
  • 您应该使用 std::unique_ptr 而不是原始拥有指针。